LARAVEL 8 - Eloquent Model without database importing data from API

Viewed 48

I'm quite new to Laravel but I realy appreciate the Eloquent Model structure. I've used for some project the base implementation (models linked to specific tables, pivot tables and so on).

For a new project I need to retrive the datas of each Model without directly connecting Laravel to a database but retriving them from external API calls (ex.: call to retrive a single "post" return jsonarray with post and post comments data)

That is the best way to achieve this keeping all "Eloquent Model benefits"? (ex: $comments = $post->comments(); to retrive all the comments of a post?)

1 Answers

Basically, there is no perfect way to use the Eloquent Model for data from API. The Eloquent Model is based on lumen framework, which makes easy to connect and query to DBMS. In addition, most APIs have different end points and HTTP methods for each CRUD actions. It makes hard to make model layer for calling API.

However, if you are willing to accept some imperfections, there are two options.

The first is developing your own model layer class having similar syntax as Eloquent. The Eloquent Model is just one of model layer class, then we can make own model layer like this:

class EloquentAPIModel
{
    protected string $url = '';     
    
    public function get(): Collection
    {
         return collect(json_decode(Http::get($this->url), true));
    }
    
    public function first(): Collection
    {
         return collect(json_decode(Http::get($this->url . '?limit=1'), true));
    }
}

class User extend EloquentAPIModel
{
    public function __construct()
    {
        $this->url = 'https://myapi.domain/api/user';
    }
}

The second option is using the cristal/php-api-wrapper. It is well-made API wrapper which provide most same syntax to the Eloquent Model. This is example code for replacing the Eloquent Model class to Cristal ApiWapper Model class:

// You must create a link between Api Wrapper instance and your model.

use Cristal\ApiWrapper\Bridges\Laravel\Model;

class MyModel extends Model
{
    // Nothing here
}


// Next, create a model that represents your object :

class User extends MyModel
{
    protected $entity = 'user';
    protected $primaryKey = 'id';
}

You will be able to find it on packagist.org and install simply using composer. You want to get more information, open the official website and look the article "Start with Laravel."

Related