Laravel и поддержка Restful API по-своему. для этого
- вы создаете свой контроллер в папке Api:
php artisan make:controller Api/TestController
определяете свои маршруты в routes/api.php
:
Route::group(['namespace' => 'Api'], function (){
Route::group(['prefix' => '/test'], function () {
Route::get('/', 'TestController@list);
Route::get('/single', 'TestController@single');
});
});
создать коллекцию ресурсов для данных, которая является массивом коллекции
php artisan make:resource Api/Collections TestCollection
эта команда создает коллекцию в папке app/Http/Resources/Api/Collections
, открывает и изменяет toArray($request)
функцию и добавляет функцию with($request)
например, следующий код:
public function toArray($request)
{
return $this->collection->map(function ($item){
return [
'id' => $item->id, // $item is instance of Test model
'name' => $item->name,
'description' => $item->description,
];
});
}
public function with($request) // optional : this method return with of response
{
return [
'status' => true
];
}
, поэтому go для TestController и создайте метод для получения всех тестов:
public function list()
{
$tests = Test::all(); // your Test Model
return new TestCollection($test); // TestCollection you created above
}
this возвращает объект json, содержащий массив тестов.
для получения одного теста: php artisan make:resource Api/Resources TestResource
затем go в TestResource в app/Http/Resources/Api/Collections
и измените код следующим образом:
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name, // $this is instance of Test model
'description' => $this->description,
'body' => $this->body,
'diff_name' => $this->name_in_table // you can change the name differ from name in model instance
];
}
так go на TestController и создайте метод для одиночного теста
public function single(Request $request)
{
$test = Test::findOrFail($request->id);
return new TestResource($test);
}
это сводка Rest API в laravel. Надеюсь, вы найдете это полезным