2 回答

TA貢獻(xiàn)1982條經(jīng)驗 獲得超2個贊
要獲取所有數(shù)據(jù),只需使用->all()
UserResource::collection($users)->all()
您可以在有關(guān)集合的官方文檔中看到更多信息,其中解釋說 usingall()
為您提供集合所表示的底層數(shù)組。

TA貢獻(xiàn)1846條經(jīng)驗 獲得超7個贊
如果您想使用自定義鍵而不是數(shù)據(jù),您可以在資源類上定義 $wrap 屬性:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class User extends JsonResource
{
/**
* The "data" wrapper that should be applied.
*
* @var string
*/
public static $wrap = 'user';
}
如果您想禁用“數(shù)據(jù)”鍵而不是數(shù)據(jù),您可以在資源類上定義 $wrap = null屬性:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class User extends JsonResource
{
/**
* The "data" wrapper that should be applied.
*
* @var string
*/
public static $wrap = null;
}
如果您想禁用最外層資源的包裝,您可以在基礎(chǔ)資源類上使用 withoutWrapping 方法。通常,您應(yīng)該從 AppServiceProvider 或其他服務(wù)提供者調(diào)用此方法,該服務(wù)提供者會在對應(yīng)用程序的每個請求中加載:
<?php
namespace App\Providers;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
JsonResource::withoutWrapping(); // This command removes "data" key from all classes extended from "JsonResource"
user::withoutWrapping(); // This command removes "data" key from only "user"
}
}
您也可以參考以下官方鏈接了解更多信息: https ://laravel.com/docs/8.x/eloquent-resources#data-wrapping
- 2 回答
- 0 關(guān)注
- 114 瀏覽
添加回答
舉報