Cách tạo bộ điều khiển API trong Laravel

Các phương thức API CRUD cơ bản có thể được mở rộng cho các mô hình của bạn theo mặc định có một danh sách, hiển thị, cập nhật, thêm và xóa điểm cuối để tương tác với mô hình của bạn

Cài đặt

Cài đặt qua nhà soạn nhạc

composer require phpsa/laravel-api-controller

Xuất bản tệp cấu hình [tùy chọn - nếu bạn cần thay đổi bất kỳ cấu hình mặc định nào]

php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"

Cách sử dụng

Lệnh CLI

  • php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    3 để tạo bộ điều khiển
  • php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    4 để tạo tệp chính sách
  • php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    5 để tạo tài nguyên phản hồi

Điều này sẽ tạo một Api/ModelNameController cho bạn và bạn sẽ có các route cơ bản như sau

  • NHẬN
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    6 - liệt kê tất cả/trang/bộ lọc [lớp. mục lục]
  • NHẬN
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    7 - Hiển thị id được chỉ định [lớp. trình diễn]
  • BÀI
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    6 - Chèn một bản ghi mới [lớp. cửa hàng]
  • PUT
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    7 - Thay thế một bản ghi hiện có [lớp. cập nhật]
  • PATCH
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    7 - Cập nhật một bản ghi hiện có [lớp. cập nhật]
  • DELETE
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    7 - Xóa một bản ghi hiện có [lớp. hủy hoại]

Nếu bạn chỉ định tùy chọn

	protected $resourceSingle = UserResource::class;
	protected $resourceCollection = UserCollection::class;
2 trên
	protected $resourceSingle = UserResource::class;
	protected $resourceCollection = UserCollection::class;
3, nó cũng sẽ tạo thêm một điểm cuối & tuyến đường của bộ điều khiển
	protected $resourceSingle = UserResource::class;
	protected $resourceCollection = UserCollection::class;
4

  • PATCH
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    7 - Khôi phục bản ghi đã xóa mềm [lớp. khôi phục]. Điều này chỉ hoạt động đối với các kiểu máy đã bật Xóa mềm

Bạn có thể ghi đè các phương thức bằng cách chỉ cần đặt các phương thức của riêng bạn để ghi đè - tên phương thức trong dấu ngoặc nhọn ở trên

Sự kiện

  • BÀI [lớp. store] - kích hoạt một Sự kiện
    	protected $resourceSingle = UserResource::class;
    	protected $resourceCollection = UserCollection::class;
    6 mới có sẵn bản ghi mới là
    	protected $resourceSingle = UserResource::class;
    	protected $resourceCollection = UserCollection::class;
    7
  • PUT [lớp. update] - kích hoạt một Sự kiện
    	protected $resourceSingle = UserResource::class;
    	protected $resourceCollection = UserCollection::class;
    8 mới có sẵn bản ghi được cập nhật là
    	protected $resourceSingle = UserResource::class;
    	protected $resourceCollection = UserCollection::class;
    7
  • XÓA [lớp. hủy] - kích hoạt Sự kiện
    public function scopeAgeNull[Builder $builder, $isNull = true]{
      $isNull ? $builder->whereNull['age'] : $builder->whereNotNull['age'];
    }
    0 mới có sẵn bản ghi đã xóa dưới dạng
    	protected $resourceSingle = UserResource::class;
    	protected $resourceCollection = UserCollection::class;
    7

chính sách

chính sách.

Tạo với

public function scopeAgeNull[Builder $builder, $isNull = true]{
  $isNull ? $builder->whereNull['age'] : $builder->whereNotNull['age'];
}
2

  • Nhận danh sách - gọi chính sách
    public function scopeAgeNull[Builder $builder, $isNull = true]{
      $isNull ? $builder->whereNull['age'] : $builder->whereNotNull['age'];
    }
    3
  • Độc thân - gọi chính sách
    public function scopeAgeNull[Builder $builder, $isNull = true]{
      $isNull ? $builder->whereNull['age'] : $builder->whereNotNull['age'];
    }
    4
  • Đăng Mới - gọi chính sách
    public function scopeAgeNull[Builder $builder, $isNull = true]{
      $isNull ? $builder->whereNull['age'] : $builder->whereNotNull['age'];
    }
    5
  • Đặt Cập nhật - gọi chính sách
    public function scopeAgeNull[Builder $builder, $isNull = true]{
      $isNull ? $builder->whereNull['age'] : $builder->whereNotNull['age'];
    }
    6
  • Xóa mục - gọi chính sách
    public function scopeAgeNull[Builder $builder, $isNull = true]{
      $isNull ? $builder->whereNull['age'] : $builder->whereNotNull['age'];
    }
    7

Công cụ sửa đổi truy vấn/dữ liệu trong chính sách dành cho điểm cuối api

  • public function scopeAgeNull[Builder $builder, $isNull = true]{
      $isNull ? $builder->whereNull['age'] : $builder->whereNotNull['age'];
    }
    8 -> return void - thêm bất kỳ truy vấn nào vào kho lưu trữ [tức là ->where['x',']]
  • public function scopeAgeNull[Builder $builder, $isNull = true]{
      $isNull ? $builder->whereNull['age'] : $builder->whereNotNull['age'];
    }
    9-> return void - thêm bất kỳ truy vấn nào vào kho lưu trữ [tức là ->where['x',']]
  • where json_unquote[json_extract[`meta\`, '$."seo"']] = 'enabled'
    
    0 - trả về mảng dữ liệu đã cập nhật
  • where json_unquote[json_extract[`meta\`, '$."seo"']] = 'enabled'
    
    1 - trả về mảng dữ liệu đã cập nhật

Tài nguyên / Bộ sưu tập [Chuyển đổi]

Tài nguyên. https. // ấu trùng. com/docs/6. x/tài nguyên hùng hồn

Tạo với

where json_unquote[json_extract[`meta\`, '$."seo"']] = 'enabled'
2 và
where json_unquote[json_extract[`meta\`, '$."seo"']] = 'enabled'
3

Thay đổi Tài nguyên để mở rộng từ

sử dụng

where json_unquote[json_extract[`meta\`, '$."seo"']] = 'enabled'
4 để sử dụng tài nguyên của bạn
where json_unquote[json_extract[`meta\`, '$."seo"']] = 'enabled'
5 để thu thập tài nguyên của bạn

trong bộ điều khiển của bạn ghi đè các thông số sau

	protected $resourceSingle = UserResource::class;
	protected $resourceCollection = UserCollection::class;

rắn vs lạc đà

  • phần mềm trung gian để chuyển đổi tất cả lạc đà thành rắn.
    where json_unquote[json_extract[`meta\`, '$."seo"']] = 'enabled'
    
    6
  • đặt tiêu đề yêu cầu
    where json_unquote[json_extract[`meta\`, '$."seo"']] = 'enabled'
    
    7 thành
    where json_unquote[json_extract[`meta\`, '$."seo"']] = 'enabled'
    
    8 hoặc
    where json_unquote[json_extract[`meta\`, '$."seo"']] = 'enabled'
    
    9 để thay đổi phản hồi dữ liệu của bạn

lọc

tùy chọn ổn định sẽ bị xóa sau khi ổn định thử nghiệm

Đối với lệnh get, bạn có thể lọc bằng cách sử dụng các mẫu url sau

SeperatorDescriptionExampleResult
protected function getNewQuery[]: Builder
    {
        return resolve[$this->model[]]->newQuery[];
    }
0Equals?filter[field]=helloselect .. where field = 'hello'
protected function getNewQuery[]: Builder
    {
        return resolve[$this->model[]]->newQuery[];
    }
1Not Equals?filter[field!]=helloselect .. where field != 'hello'
protected function getNewQuery[]: Builder
    {
        return resolve[$this->model[]]->newQuery[];
    }
2Not Equals [alt]?filter[field]=helloselect .. where field != 'hello'
protected function getNewQuery[]: Builder
    {
        return resolve[$this->model[]]->newQuery[];
    }
3Greater Than?filter[field>]=5select .. where field > 5
protected function getNewQuery[]: Builder
    {
        return resolve[$this->model[]]->newQuery[];
    }
4Greater Or Equal to?filter[field>=]=5select .. where field >= 5
protected function getNewQuery[]: Builder
    {
        return resolve[$this->model[]]->newQuery[];
    }
5Less Than?filter[fieldmodel[]]->newQuery[]; } 6Less Or Equal to?filter[fieldnewQuery[]; } 7Contains [LIKE with wildcard on both sides]?filter[field~]=helloselect .. where field like '%hello%'
protected function getNewQuery[]: Builder
    {
        return resolve[$this->model[]]->newQuery[];
    }
8Starts with [LIKE with wildcard on end]?filter[field^]=helloselect .. where field like 'hello%'
protected function getNewQuery[]: Builder
    {
        return resolve[$this->model[]]->newQuery[];
    }
9Ends with [LIKE with wildcard on start]?filter[field$]=helloselect .. where field like 'hello%'
protected static $allowedScopes = [
  'fullname'
];
0Not Contains [LIKE with wildcard on both sides]?filter[field!~]=helloselect .. where field not like '%hello%'
protected static $allowedScopes = [
  'fullname'
];
1Not Starts with [LIKE with wildcard on end]?filter[field!^]=helloselect .. where field not like 'hello%'
protected static $allowedScopes = [
  'fullname'
];
2Not Ends with [LIKE with wildcard on start]?filter[field!$]=helloselect .. where field not like 'hello%'In / Not In

Bạn có thể chuyển đến các bộ lọc một mảng các giá trị tức là.

protected static $allowedScopes = [
  'fullname'
];
3 hoặc
protected static $allowedScopes = [
  'fullname'
];
4

Null/Not Null [giới thiệu 1. 23. 0]

Nếu bạn cần lọc xem một trường là null hay không null, bạn có thể sử dụng tham số bộ lọc kể từ phiên bản 1. 23. 0 EG.

protected static $allowedScopes = [
  'fullname'
];
5 hoặc
protected static $allowedScopes = [
  'fullname'
];
6. Lưu ý rằng NULL phải là chữ hoa

Các phiên bản cũ hơn Thêm phạm vi vào mô hình của bạn. ví dụ

public function scopeAgeNull[Builder $builder, $isNull = true]{
  $isNull ? $builder->whereNull['age'] : $builder->whereNotNull['age'];
}

Thêm vào Phạm vi được phép của bạn và sau đó có thể được gọi trong url là

protected static $allowedScopes = [
  'fullname'
];
7 cho vị trí null và
protected static $allowedScopes = [
  'fullname'
];
8 cho vị trí age không null

Thử nghiệm v5 hiện tại

  • sử dụng mẫu url
    protected static $allowedScopes = [
      'fullname'
    ];
    9, ví dụ:
     public function scopeFilterByRelationGroup[Builder $builder, array $wheres]: void
        {
            $where =  collect[$wheres]->map[fn [$child] =>
               $this->parseFiltersArray[$child]
            ]->each[
                fn[$group, $key] => $builder->whereHas['Relation', function [$subQ] use [$group, $key] {
                    $group->each[
                        fn[$filter, $column] => collect[$filter]->each[fn[$value, $comparison] => $this->buildQuery[$column, $comparison, $value, $subQ]]
                    ];
                }
                ]
            ];
    
        }
    
    0
SeperatorDescriptionExampleResultempty /
protected function getNewQuery[]: Builder
    {
        return resolve[$this->model[]]->newQuery[];
    }
0 /
 public function scopeFilterByRelationGroup[Builder $builder, array $wheres]: void
    {
        $where =  collect[$wheres]->map[fn [$child] =>
           $this->parseFiltersArray[$child]
        ]->each[
            fn[$group, $key] => $builder->whereHas['Relation', function [$subQ] use [$group, $key] {
                $group->each[
                    fn[$filter, $column] => collect[$filter]->each[fn[$value, $comparison] => $this->buildQuery[$column, $comparison, $value, $subQ]]
                ];
            }
            ]
        ];

    }
2 /
 public function scopeFilterByRelationGroup[Builder $builder, array $wheres]: void
    {
        $where =  collect[$wheres]->map[fn [$child] =>
           $this->parseFiltersArray[$child]
        ]->each[
            fn[$group, $key] => $builder->whereHas['Relation', function [$subQ] use [$group, $key] {
                $group->each[
                    fn[$filter, $column] => collect[$filter]->each[fn[$value, $comparison] => $this->buildQuery[$column, $comparison, $value, $subQ]]
                ];
            }
            ]
        ];

    }
3Equals?filters[field]=hello / ?filters[field][is]=helloselect .. where field = 'hello'
protected function getNewQuery[]: Builder
    {
        return resolve[$this->model[]]->newQuery[];
    }
1 /
 public function scopeFilterByRelationGroup[Builder $builder, array $wheres]: void
    {
        $where =  collect[$wheres]->map[fn [$child] =>
           $this->parseFiltersArray[$child]
        ]->each[
            fn[$group, $key] => $builder->whereHas['Relation', function [$subQ] use [$group, $key] {
                $group->each[
                    fn[$filter, $column] => collect[$filter]->each[fn[$value, $comparison] => $this->buildQuery[$column, $comparison, $value, $subQ]]
                ];
            }
            ]
        ];

    }
5 /
 public function scopeFilterByRelationGroup[Builder $builder, array $wheres]: void
    {
        $where =  collect[$wheres]->map[fn [$child] =>
           $this->parseFiltersArray[$child]
        ]->each[
            fn[$group, $key] => $builder->whereHas['Relation', function [$subQ] use [$group, $key] {
                $group->each[
                    fn[$filter, $column] => collect[$filter]->each[fn[$value, $comparison] => $this->buildQuery[$column, $comparison, $value, $subQ]]
                ];
            }
            ]
        ];

    }
6 /
 public function scopeFilterByRelationGroup[Builder $builder, array $wheres]: void
    {
        $where =  collect[$wheres]->map[fn [$child] =>
           $this->parseFiltersArray[$child]
        ]->each[
            fn[$group, $key] => $builder->whereHas['Relation', function [$subQ] use [$group, $key] {
                $group->each[
                    fn[$filter, $column] => collect[$filter]->each[fn[$value, $comparison] => $this->buildQuery[$column, $comparison, $value, $subQ]]
                ];
            }
            ]
        ];

    }
7Not Equals?filter[field][!is]=helloselect .. where field != 'hello'
protected function getNewQuery[]: Builder
    {
        return resolve[$this->model[]]->newQuery[];
    }
3 /
 public function scopeFilterByRelationGroup[Builder $builder, array $wheres]: void
    {
        $where =  collect[$wheres]->map[fn [$child] =>
           $this->parseFiltersArray[$child]
        ]->each[
            fn[$group, $key] => $builder->whereHas['Relation', function [$subQ] use [$group, $key] {
                $group->each[
                    fn[$filter, $column] => collect[$filter]->each[fn[$value, $comparison] => $this->buildQuery[$column, $comparison, $value, $subQ]]
                ];
            }
            ]
        ];

    }
9Greater Than?filter[field][greater_than]=5select .. where field > 5
protected function getNewQuery[]: Builder
    {
        return resolve[$this->model[]]->newQuery[];
    }
4 /
protected static array $fieldGates = [
    'gate-one' => [
        'fieldA',
        'fieldB',
     ],
     'gate-two' => [
       'fieldA',
       'fieldC,
       'relatedResourceD'
     ]
];
1 /
protected static array $fieldGates = [
    'gate-one' => [
        'fieldA',
        'fieldB',
     ],
     'gate-two' => [
       'fieldA',
       'fieldC,
       'relatedResourceD'
     ]
];
2Greater Or Equal to?filter[field][greater_or_equal]=5select .. where field >= 5
protected function getNewQuery[]: Builder
    {
        return resolve[$this->model[]]->newQuery[];
    }
5 /
protected static array $fieldGates = [
    'gate-one' => [
        'fieldA',
        'fieldB',
     ],
     'gate-two' => [
       'fieldA',
       'fieldC,
       'relatedResourceD'
     ]
];
4Less Than?filter[field][model[]]->newQuery[]; } 6 /
protected static array $fieldGates = [
    'gate-one' => [
        'fieldA',
        'fieldB',
     ],
     'gate-two' => [
       'fieldA',
       'fieldC,
       'relatedResourceD'
     ]
];
6 /
protected static array $fieldGates = [
    'gate-one' => [
        'fieldA',
        'fieldB',
     ],
     'gate-two' => [
       'fieldA',
       'fieldC,
       'relatedResourceD'
     ]
];
7Less Or Equal to?filter[field][less_or_equal]=5select .. where field model[]]->newQuery[]; } 7 /
protected static array $fieldGates = [
    'gate-one' => [
        'fieldA',
        'fieldB',
     ],
     'gate-two' => [
       'fieldA',
       'fieldC,
       'relatedResourceD'
     ]
];
9Contains [LIKE with wildcard on both sides]?filter[field][contains]=helloselect .. where field like '%hello%'
protected function getNewQuery[]: Builder
    {
        return resolve[$this->model[]]->newQuery[];
    }
8 /
  Gate::define[
      'supervises-the-group',
      fn [$user, Group $group] => [int] $user->id === $group->supervisor_id
  ];
1Starts with [LIKE with wildcard on end]?filter[field][starts_with]=helloselect .. where field like 'hello%'
protected function getNewQuery[]: Builder
    {
        return resolve[$this->model[]]->newQuery[];
    }
9 /
  Gate::define[
      'supervises-the-group',
      fn [$user, Group $group] => [int] $user->id === $group->supervisor_id
  ];
3Ends with [LIKE with wildcard on start]?filter[field][ends_with]=helloselect .. where field like 'hello%'
protected static $allowedScopes = [
  'fullname'
];
0 /
  Gate::define[
      'supervises-the-group',
      fn [$user, Group $group] => [int] $user->id === $group->supervisor_id
  ];
5 /
  Gate::define[
      'supervises-the-group',
      fn [$user, Group $group] => [int] $user->id === $group->supervisor_id
  ];
6Not Contains [LIKE with wildcard on both sides]?filter[field][!contains]=helloselect .. where field not like '%hello%'
protected static $allowedScopes = [
  'fullname'
];
1 /
  Gate::define[
      'supervises-the-group',
      fn [$user, Group $group] => [int] $user->id === $group->supervisor_id
  ];
8 /
  Gate::define[
      'supervises-the-group',
      fn [$user, Group $group] => [int] $user->id === $group->supervisor_id
  ];
9Not Starts with [LIKE with wildcard on end]?filter[field][!^]=helloselect .. where field not like 'hello%'
protected static $allowedScopes = [
  'fullname'
];
2 /
php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
01 /
php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
02Not Ends with [LIKE with wildcard on start]?filter[field][!$]=helloselect .. where field not like 'hello%'
php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
03in?filter[field][in]=1,2,3select .. where field in[1,2,3]
php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
04 /
php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
05NOT in?filter[field][in]=1,2,3select .. where field not in[1,2,3]
php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
06has?filter[field][has]select .. where exists[field join]
php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
07 /
php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
08NOT has?filter[field][!has]select .. where not exists [field join]
  • Null =

    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    09 sẽ tạo ra
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    10

  • Các cột Json =

    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    11 sẽ tạo

where json_unquote[json_extract[`meta\`, '$."seo"']] = 'enabled'

  • quan hệ.
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    12 hoặc
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    13 hoặc
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    14
  • Lọc quan hệ
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    15
  • Mối quan hệ
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    16 hoặc
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    17
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    18
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    19

Phạm vi thực thi/bộ lọc truy vấn trên bộ điều khiển sẽ ghi đè lên

protected function getNewQuery[]: Builder
    {
        return resolve[$this->model[]]->newQuery[];
    }

trong bộ điều khiển của bạn để bao gồm bất kỳ truy vấn/phạm vi bổ sung nào, v.v.

phạm vi

Ngoài chức năng lọc, bạn có thể sử dụng Eloquent của Laravel để thực hiện các tìm kiếm hoặc bộ lọc phức tạp hơn. Chỉ cần thêm

php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
20 vào
php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
21 của bạn và phạm vi đó sẽ được hiển thị dưới dạng tham số truy vấn

Giả sử bạn có một

php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
22 được xác định trên Mô hình Eloquent của mình, bạn có thể hiển thị phạm vi này cho API của mình như sau

protected static $allowedScopes = [
  'fullname'
];

Với mảng

php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
20 ở trên, giờ đây người tiêu dùng API của bạn sẽ có thể yêu cầu
php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
24. Giá trị tham số truy vấn sẽ được chuyển đến hàm phạm vi trong Mô hình Eloquent của bạn

Lọc trên các mô hình liên quan

Bạn có thể dễ dàng lọc bằng cách sử dụng bất kỳ mô hình liên quan nào được định cấu hình cho

php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
25. Chỉ cần chỉ định
php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
26 trong chuỗi truy vấn của bạn. Các tùy chọn bộ lọc tương tự ở trên áp dụng cho các trường liên quan

Phạm vi lọc được nhóm

php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
27

 public function scopeFilterByRelationGroup[Builder $builder, array $wheres]: void
    {
        $where =  collect[$wheres]->map[fn [$child] =>
           $this->parseFiltersArray[$child]
        ]->each[
            fn[$group, $key] => $builder->whereHas['Relation', function [$subQ] use [$group, $key] {
                $group->each[
                    fn[$filter, $column] => collect[$filter]->each[fn[$value, $comparison] => $this->buildQuery[$column, $comparison, $value, $subQ]]
                ];
            }
            ]
        ];

    }

Trường, Mối quan hệ, Sắp xếp và Phân trang

Lĩnh vực

Theo mặc định, tất cả các trường được trả về, bạn có thể giới hạn điều đó ở các trường cụ thể theo các cách sau

  • Tham số Bộ điều khiển Api
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    28 mặc định là
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    29 - chuyển sang bao gồm một mảng các trường
  • trường param trong chuỗi truy vấn url. tức là
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    30 = sẽ chỉ trả lại những cái đó, cái này cũng sẽ ghi đè lên cái trên
  • trong tài nguyên phản hồi của bạn, bạn có thể đặt tĩnh. allowFields để khóa những trường nào có thể trả lại
    • Điều này cũng kiểm soát những tài nguyên liên quan nào có thể trả lại. Bao gồm khóa được sử dụng trong
      php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
      31 [xem "Mối quan hệ" bên dưới]
  • Các thông số
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    32 và
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    33 trong chuỗi truy vấn url sẽ hoạt động với các thông số này
  • Sử dụng thuộc tính laravel để tự động bao gồm các bộ truy cập thuộc tính tùy chỉnh

Các trường phản hồi có kiểm soát

Cổng có thể được sử dụng để kiểm soát quyền truy cập vào các trường và tài nguyên liên quan, bằng cách xác định

php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
35

protected static array $fieldGates = [
    'gate-one' => [
        'fieldA',
        'fieldB',
     ],
     'gate-two' => [
       'fieldA',
       'fieldC,
       'relatedResourceD'
     ]
];

Mỗi cổng được chỉ định sẽ được sử dụng để xác định xem tập hợp các trường đó có được đưa vào hay không

Mỗi cổng sẽ được thông qua tài nguyên cũng như người dùng, do đó, nó có thể kiểm tra xem người dùng có được phép truy cập vào tài nguyên cụ thể đó hay không

Định nghĩa cổng ví dụ

  Gate::define[
      'supervises-the-group',
      fn [$user, Group $group] => [int] $user->id === $group->supervisor_id
  ];

Các mối quan hệ

  • Sử dụng các mối quan hệ được xác định trong các mô hình của bạn, bạn có thể chuyển một danh sách được phân cách bằng dấu phẩy, ví dụ:
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    36 sẽ trả về các phép nối đó [một hoặc nhiều]

Chỉ cần thêm

php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
37 vào
php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
38 của bạn để xác định tài nguyên nào sẽ chỉ định dữ liệu liên quan của bạn. e. e. , đối với mối quan hệ một đến nhiều, bạn nên chỉ định một bộ sưu tập và mối quan hệ một đối một chỉ định trực tiếp tài nguyên liên quan. Điều này sẽ cho phép API định dạng đúng bản ghi liên quan

php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
0

  • Bạn có thể tự động cập nhật và tạo các bản ghi liên quan cho hầu hết các loại mối quan hệ. Chỉ cần bao gồm tên tài nguyên có liên quan trong yêu cầu POST hoặc PUT của bạn
  • Quan trọng. nếu bạn đang sử dụng
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    28 và/hoặc
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    40 trong tài nguyên của mình, khóa tài nguyên liên quan từ
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    31 cũng phải được đưa vào các danh sách đó để đưa tài nguyên liên quan đó vào

Đối với các mối quan hệ

php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
42 hoặc
php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
43, bạn có thể chọn chiến lược đồng bộ hóa. Theo mặc định, điều này sẽ có một chiến lược bổ sung. Điều đó có nghĩa là, các bản ghi liên quan đã gửi sẽ được THÊM vào bất kỳ bản ghi liên quan hiện có nào. Trên cơ sở từng yêu cầu, bạn có thể chọn chiến lược đồng bộ hóa sẽ xóa trục đối với bất kỳ bản ghi liên quan nào không được liệt kê trong yêu cầu. Lưu ý rằng bản ghi liên quan thực tế sẽ không bị xóa, chỉ mục nhập trục

Để chọn hành vi đồng bộ hóa, hãy đặt

php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
44 trong yêu cầu của bạn

Sắp xếp

  • Sắp xếp cũng có thể được chuyển dưới dạng danh sách dấu phẩy, tức là
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    45 hoặc
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    46 - tạo sql lần lượt là
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    47 và
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    48
  • Sắp xếp mặc định cũng có thể được thêm vào bộ điều khiển bằng cách ghi đè tham số
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    49

phân trang

  • phân trang có thể được bật/tắt trên bộ điều khiển bằng cách ghi đè
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    50 trên bộ điều khiển
  • phân trang cũng có thể được chuyển qua url bằng cách sử dụng
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    51
  • phân trang cũng có thể được giới hạn ở mức tối đa trên mỗi trang bằng cách ghi đè tham số
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    52

Thẩm định

  • Khi Đăng một bản ghi mới, việc xác thực có thể được thực hiện bằng cách thêm phương thức
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    53 vào bộ điều khiển của bạn trả về một mảng, ví dụ:

php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
1

thấy

  • để cập nhật bản ghi, hãy thêm phương thức
    php artisan vendor:publish --provider="Phpsa\LaravelApiController\ServiceProvider" --tag="config"
    54 ở trên

Mặc định

Các tham số sau được đặt trong bộ điều khiển Api cơ sở và có thể được ghi đè bởi Bộ điều khiển của bạn trong từng trường hợp

Làm cách nào để tạo lệnh điều khiển trong Laravel?

Bước 1 − Tạo bộ điều khiển có tên MyController bằng cách thực hiện lệnh sau. app/Http/Controllers/MyController. tệp php . Bước 3 - Thêm dòng mã sau vào app/Http/routes.

Làm cách nào để tạo API trong Laravel?

Các bước để tạo API REST trong Laravel 8. .
Bước 1. Cài đặt Laravel 8. .
Bước 2. cấu hình cơ sở dữ liệu. .
Bước 3. Tạo một bảng. .
Bước 4. Thêm tuyến tài nguyên. .
Bước 5. Thêm bộ điều khiển và mô hình. .
Bước 6. Chạy ứng dụng CRUD. .
Bước 7. thử nghiệm

Lệnh nào được sử dụng để tạo bộ điều khiển Laravel?

Bộ điều khiển cơ bản . get['/user/{id}', [UserController. class, 'show']]; Route::get['/user/{id}', [UserController::class, 'show']]; Khi một yêu cầu đến phù hợp với URI tuyến đã chỉ định, phương thức hiển thị trên lớp App\Http\Controllers\UserController sẽ được gọi và các tham số tuyến sẽ được chuyển .

Làm cách nào để tạo API trong Laravel 7 từng bước?

API REST của Laravel 7/6 với Hướng dẫn về hộ chiếu .
Bước 1. Cài đặt Laravel 6. .
Bước 2. Sử dụng hộ chiếu. .
Bước 3. Cấu hình hộ chiếu. .
Bước 4. Thêm bảng sản phẩm và mô hình. .
Bước 5. Tạo các tuyến API. .
Bước 6. Tạo tập tin điều khiển. .
Bước 7. Tạo tài nguyên API Eloquent

Chủ Đề