Illuminate\Http\Resources\Json\ResourceCollection 的使用
ResourceCollection 是用于处理 返回值为json的时候定义返回的集合的格式,集合内的单个元素可以使用 Illuminate\Http\Resources\Json\JsonResource 定义,或者直接在toArray中重新定义。
use App\User;
use App\Http\Resources\User as UserResource;
Route::get('/user', function () {
return UserResource::collection(User::all());
});
// 如果定义了Collection
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class UserCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'data' => $this->collection,
'links' => [
'self' => 'link-value',
],
];
}
}
// 新的写法
use App\User;
use App\Http\Resources\UserCollection;
Route::get('/users', function () {
return new UserCollection(User::all());
});
评论已关闭