php - Use Laravel to consume an external Laravel API

Solution:

You have to use the http-client. Laravel provides already one, based on Guzzle.

So, in order to update something You have to create PUT route on Your Server and then just call it from Client like this:

$response = Http::put("https://YOUR.SERVER/organisations/$id", [
    'name' => 'Steve',
    'role' => 'Network Administrator',
]);

More info, You will find in Laravel Documentation

Answer

Solution:

if you want to use the Laravel as a frontend client to consume a remote API it easy, a part the fact that you can consider the use of vue.js as your frontend in order to keep things simpler.

FRONTEND

  1. Create the Laravel project as usual, the only difference is that you don't need to set up the database and migrations

  2. You are going to use the normal MVC pattern here, so in your Frontend FlightController class, you will fetch the data like this.

getFlights()
{
    $response = Http::get(env('API_URL') . '/flights')->json();
}

we can optionally install the package spatie/data-transfer-object in order to convert your json data to DTO object like this:


getFlights()
{
    $flights_data = Http::get(env('API_URL') . '/flights')->json();

    $filghts = [];

    foreach($flight_data as data)
       $filghts->add(new \App\Models\Dto\FlightDto($data));
    
    return view('flights.search-result', compact('filghts'));
}

the DTO class looks like this:

use Spatie\DataTransferObject\DataTransferObject;

class FlightDto extends DataTransferObject
{
    /** @var integer|null */
    public $id;

    /** @var string|null */
    public $flight_number;
}

The authentication is little bit tricky, refer to this question to see how you can create custom user provider.

BACKEND

  1. Create a Laravel project, set up database and all your migrations

  2. place all your routes in the default location api.php

Route::get('/trips', 'ApiTripsController@getFlights');

3- in the FlightsController do the following

public getFlights
{
   return Flight::all() // where the Flight class is the Eloquent model
}

do not forget to provide a security layer to protect ressources from the server side

Source