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."