php artisan make:resource Dog
Example 13-17. Generated API resource
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Dog extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
}
我们在这里使用的toArray()方法可以访问两个重要的数据。 首先,它可以访问Illuminate Request对象,因此我们可以根据查询参数和头以及其他任何重要的内容自定义响应。 第二,它可以通过在$ this上调用它的属性和方法来访问整个Eloquent对象,如例13-18所示。
Example 13-18. Simple API resource for the Dog model
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Dog extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'breed' => $this->breed,
];
}
}
Example 13-19. Using the simple Dog resource
use App\Dog;
use App\Http\Resources\Dog as DogResource;
Route::get('dogs/{dogId}', function ($dogId) {
return new DogResource(Dog::find($dogId));
});