编程

[Laravel 扩展包]使用 LARAVEL Restify 包创建 API

918 2022-08-01 09:57:32

Laravel Restify 是一个包,用于制作与Laravel兼容的强大JSON:API Rest API。安装软件包并遵循安装指南后,您可以使用repository CLI快速入门:

php artisan restify:repository Dream --all

repository 是这个软件包的核心。上面的示例命令将生成一个空 repository :

namespace App\Restify;
 
use App\Models\Dream;
use Binaryk\LaravelRestify\Http\Requests\RestifyRequest;
 
class DreamRepository extends Repository
{
    public static string $model = Dream::class;
 
    public function fields(RestifyRequest $request): array
    {
        return [
            id(),
            field('title')->required(),
            field('description'),
            field('image')->image(),
        ];
    }
}

如果您没有定义$model属性,Restify可以根据存储库类名进行猜测(即DreamRepository将是Dream模型)。

下面是一个内置UserRepository类的示例(您希望在实际应用程序中保护它),它将以JSON API格式返回API响应:

GET: /api/restify/users?perPage=10&page=2
{
  "meta": {
    "current_page": 1,
    "from": 1,
    "last_page": 1,
    "path": "http://localhost:8000/api/restify/users",
    "per_page": 15,
    "to": 1,
    "total": 1
  },
  "links": {
    "first": "http://localhost:8000/api/restify/users?page=1",
    "next": null,
    "path": "http://localhost:8000/api/restify/users",
    "prev": null,
    "filters": "/api/restify/users/filters"
  },
  "data": [
    {
      "id": "1",
      "type": "users",
      "attributes": {
        "name": "Paul Redmond",
        "email": "paul@example.com"
      }
    }
  ]
}

此软件包还将引导您完成身份验证过程、高级过滤等!