我遇到了一个从控制器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中不再是一个集合
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')),上指定排除的字段,这些字段已经在这里停留了一段时间。
发布于 2021-09-09 18:00:30
经过研究,我为我的问题找到了一个可行的解决方案
'company' => CompanyResource::make($this->whenLoaded('company'))->hide(['company_logo']),而不是我不能灵活使用的以下代码:
'company' => new CompanyResource($this->whenLoaded('company')),https://stackoverflow.com/questions/69104301
复制相似问题