Multiple Apis With ForwardsCalls Trait - Laravel

morcosgad

Morcos Gad

Posted on December 20, 2021

Multiple Apis With ForwardsCalls Trait - Laravel

Let's start quickly. I found an advanced way to call the api via ForwardsCalls and I want to share it with you.
First you create an Api.php page

<?php

namespace App\Http\Apis;

use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Traits\ForwardsCalls;

abstract class Api
{
    use ForwardsCalls;

    protected PendingRequest $http;

    public function __construct()
    {
        $this->http = $this->initialize();
    }

    public function __call($method, $params)
    {
        return $this->forwardCallTo($this->http, $method, $params);
    }

    public abstract function initialize(): PendingRequest;
}
Enter fullscreen mode Exit fullscreen mode

Create a Laratips Api.php page to take from the previous page

<?php

namespace App\Http\Apis;

use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;

class LaratipsApi extends Api
{
    public function initialize(): PendingRequest
    {
        return Http::acceptJson()->baseUrl('http://laratips.test/api');
    }
}
Enter fullscreen mode Exit fullscreen mode

So we come to the summons

<?php

namespace App\Http\Controllers;

use App\Http\Apis\LaratipsApi;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class DashboardController extends Controller
{
    public function index(Request $request)
    {
        return (new LaratipsApi)->get('users');
    }
}
Enter fullscreen mode Exit fullscreen mode

It is also possible to call fakeapi and take a certain part of it I create a FakeStoreApi.php page

<?php

namespace App\Http\Apis;

use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;

class FakeStoreApi extends Api
{
    public function initialize(): PendingRequest
    {
        return Http::acceptJson()->baseUrl('https://fakestoreapi.com');
    }    
}
Enter fullscreen mode Exit fullscreen mode

So we come to the summons

<?php

namespace App\Http\Controllers;

use App\Http\Apis\FakeStoreApi;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class DashboardController extends Controller
{
    public function index(Request $request)
    {
        return (new FakeStoreApi)->get('products', [
            'limit' => 2
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Source :- https://github.com/Laratipsofficial/tips-and-tricks/tree/laravel-feature/forwards-calls
Source :- https://www.youtube.com/watch?v=vzgNm86ezWE

I hope you enjoyed the code.

💖 💪 🙅 🚩
morcosgad
Morcos Gad

Posted on December 20, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related