Laravel 8 資源集合

2021-07-19 11:46 更新

你可以在路由或者控制器中使用 collection 方法來創(chuàng)建資源實(shí)例,以返回多個(gè)資源的集合或分頁響應(yīng):

use App\Http\Resources\User as UserResource;
use App\Models\User;

Route::get('/user', function () {
    return UserResource::collection(User::all());
}); 

當(dāng)然了,使用如上方法你將不能添加任何附加的元數(shù)據(jù)和集合一起返回。如果你需要自定義資源集合響應(yīng),你需要?jiǎng)?chuàng)建一個(gè)專用的資源來表示集合:

php artisan make:resource UserCollection  

你可以輕松地在已生成的資源集合類中定義任何你想在響應(yīng)中返回的元數(shù)據(jù):

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class UserCollection extends ResourceCollection
{
    /**
     * 將資源集合轉(zhuǎn)換成數(shù)組
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'data' => $this->collection,
            'links' => [
                'self' => 'link-value',
            ],
        ];
    }
} 

你可以在路由或者控制器中返回已定義的資源集合:

use App\Http\Resources\UserCollection;
use App\Models\User;

Route::get('/users', function () {
    return new UserCollection(User::all());
}); 
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)