从资源模板 Laravel 7 和 8 中排除字段
Posted
技术标签:
【中文标题】从资源模板 Laravel 7 和 8 中排除字段【英文标题】:Exclude fields from a Resource template Laravel 7 and 8 【发布时间】:2021-11-05 07:12:23 【问题描述】:我遇到了一个解决方案,可以从 Controller CompanyController.php
中的资源集合中过滤字段
例如下面的代码返回除company_logo
之外的所有值
CompanyResource::collection($companies)->hide(['company_logo']);
CompanyResource.php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class CompanyResource extends JsonResource
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
protected $withoutFields = [];
public static function collection($resource)
return tap(new CompanyResourceCollection($resource), function ($collection)
$collection->collects = __CLASS__;
);
// Set the keys that are supposed to be filtered out
public function hide(array $fields)
$this->withoutFields = $fields;
return $this;
// Remove the filtered keys.
protected function filterFields($array)
return collect($array)->forget($this->withoutFields)->toArray();
public function toArray($request)
return $this->filterFields([
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'telephone' => $this->telephone,
'company_logo' => $this->company_logo,
'social_links' => $this->social_links,
]);
现在从我的UserResource
我仍然想指定我不想从同一个CompanyResource
返回的字段,但它不再是UserResource
中的集合
用户资源.php
public function toArray($request)
return [
'id' => $this->id,
'email' => $this->email,
'status' => $this->status,
'timezone' => $this->timezone,
'last_name' => $this->last_name,
'first_name' => $this->first_name,
'tags' => TagResource::collection($this->whenLoaded('tags')),
'company' => new CompanyResource($this->whenLoaded('company')),
];
所以我的想法是能够在'company' => new CompanyResource($this->whenLoaded('company')),
上指定排除字段 在这里停留了一段时间。
【问题讨论】:
【参考方案1】:经过研究,我找到了解决问题的有效解决方案
'company' => CompanyResource::make($this->whenLoaded('company'))->hide(['company_logo']),
下面的我不能灵活使用:
'company' => new CompanyResource($this->whenLoaded('company')),
【讨论】:
以上是关于从资源模板 Laravel 7 和 8 中排除字段的主要内容,如果未能解决你的问题,请参考以下文章