madeweb/eloquent-api

支持API的Eloquent模型,是用于封装如何使用端点来建模实体的包装器。

v0.1 2020-01-06 12:45 UTC

This package is auto-updated.

Last update: 2024-09-29 05:29:40 UTC


README

Packagist GitHub stars

此包允许使用API资源使用模型和关系。

安装

composer require madeweb/eloquent-api

生成调用API的模型包装器

php artisan make:model-api Model --api=API\\NameOfAPI 

生成与Passport进行身份验证的模型包装器

php artisan make:model-api Model --api=API\\NameOfAPI --auth

配置

在模型中使用fillable

设置fillable非常重要,因为这个变量允许识别模型中将有字段。

    protected $fillable = ['uuid', 'name', 'last_name', 'phone', 'document_type', 'document_number',
        'birthdate', 'civil_status', 'gender', 'address_uuid', 'user_uuid'];

关系

为了准备模型之间的关系,需要使用此语法。例如,对于人员模型,参数的顺序是类属于、标识关系的键、两个模型中共同的关键字或字段,以及连接API的方法。

    public function user()
    {
        return $this->relationship(User::class, 'user', $this->user_uuid, 'find');
    }

基本方法

由于它是一个API,因此需要定义自己的函数来调用Eloquent中存在的基本方法。例如,在这个函数中,API中必须存在showPerson方法。

    public function find($uuid)
    {
        $response = $this->connection->showPerson($uuid);
        return $this->prepareResponse($response);
    }