How to use Ionic with Laravel Route as an API to send data?

The ionic platform provides the HTTP client method to post or get data to and from the database. We can use this library to send database information with the help of an API. We can pass an API url along with the input parameters to send data to the API. It then further handles our input from the mobile application and saves it to the database. Learn how to use Ionic with Laravel Route using the tutorial below.

Steps to create a Laravel API

You can create an API service using Laravel following the few simple steps given below.

  1. Create a new migration for your table using the command below.
php artisan migrate --path=/database/migrations/

If your Laravel application is already connected with your database (check .env file), this will create a new table. 

  1. Create a new model for your table.
php artisan make::Model Notifications

Your Model should have the contents as shown below. 

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Notification extends Model
{
    use HasFactory;
	protected $fillable = [
        "contact", "email", "birth_date",
        "star", "push_stat", "notification_status",
        "device_token"
    ];

}
  1. Now create a new route using the Modal as given below.
Route::get('/save-push-data/{token}/{status}/{app_id}',
function($token,$status,$app_id){
    
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST');
    header("Access-Control-Allow-Headers: X-Requested-With");
    
    Notification::updateOrCreate([
            "token" => $token,
            "app_id" => $app_id
            ], [
            "status" => $status
    ]);
});

This route handles your Device Modal data, it takes in the parameters entered and saves their input fields to the database. We can use this route in our Ionic Application along with the httpClient module. 

Steps to set up the HttpClient Module in Ionic Application

  1. Add the HttpClient dependency to your Ionic Application.
  2. Import the module in your app.module.ts file and add in the providers section.
  3. Import the module in your Ionic component files and use it in any function. 
import { HttpClient } from '@angular/common/http';
  1. The httpClient.post method can be used in your app as given below. 
this.httpClient.get('https://scratchcoding.dev/save-data/'+this.token+'/'+this.status+'/+this.app_id)
        .subscribe(response => {
          console.log('data: ', response);
        });

Pass the URL along with desired parameters, the one you need to send to database. 

https://scratchcoding.dev/save-data/'+this.token+'/'+this.status+'/+this.app_id

The Laravel route here works as an API, it is the middleware that connects your Ionic Application to your database. It allows us to easily send and receive data to and from databases for our ionic mobile applications.