簡體   English   中英

Laravel eloquent api resource remove `data` key (no collection)

[英]Laravel eloquent api resource remove `data` key (no collection)

我為user定制了 eloquent api 資源。 例如當我使用這個資源時

代碼

$user = $request->user();
return new UserResource($user);

然后我得到回應:

{
    "data": {
        "name": "Margarete Daniel",
        "email": "goldner.berniece@example.net",
        "verified": "2020-03-20T07:15:56.000000Z"
    }
}

我如何更改 api 資源並獲得示例響應:

{
    "name": "Margarete Daniel",
    "email": "goldner.berniece@example.net",
    "verified": "2020-03-20T07:15:56.000000Z"
}

您可以通過在AppServiceProvider調用資源的withoutWrapping靜態方法來禁用數據包裝。 在您的情況下,它將是:

public function boot()
{
    UserResource::withoutWrapping();
}

你可以參考Laravel 文檔中關於數據包裝的更多解釋。

將此添加到您的資源中

public static $wrap = null;

回答,因為我自己一直在同一個問題上磕磕絆絆。

在沒有data包裝的情況下返回 Laravel 資源的最簡單方法是簡單地在 JSON 響應中返回它。 所以,而不是做:

return new UserResource($user);

你會這樣做:

return response()->json(new UserResource($user));

這樣,您也不必擔心通過對withoutWrapping方法的大量調用來填充AppServiceProvider

出於某種原因,這有效:

$user = User::find(1);

return UserResource::make($user)->resolve();

沒有->resolve()它是行不通的。

要刪除項目中所有資源的數據包裝器,只需添加:

use Illuminate\Http\Resources\Json\JsonResource    

public function boot()
{
    JsonResource::withoutWrapping();
}

AppServiceProvider.phpboot方法中。

這對我有用

return UserResource::make($user)->toArray($request);

和收集

return UserResource::collection($users)->collection;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM