我假设你有一个PostResource
,如果你没有,你可以生成一个:
php artisan make:resource PostResource
PostResource
覆盖和过滤字段的收集方法:
class PostResource extends Resource
{
protected $withoutFields = [];
public static function collection($resource)
{
return tap(new PostResourceCollection($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,
'title' => $this->title,
'body' => $this->body,
'date' => $this->date
]);
}
}
你需要创建一个PostResourceCollection
php artisan make:resource --collection PostResourceCollection
这里正在使用隐藏字段处理集合
class PostResourceCollection extends ResourceCollection
{
protected $withoutFields = [];
// Transform the resource collection into an array.
public function toArray($request)
{
return $this->processCollection($request);
}
public function hide(array $fields)
{
$this->withoutFields = $fields;
return $this;
}
// Send fields to hide to UsersResource while processing the collection.
protected function processCollection($request)
{
return $this->collection->map(function (PostResource $resource) use ($request) {
return $resource->hide($this->withoutFields)->toArray($request);
})->all();
}
}
现在,您可以使用要隐藏的字段PostController
调用方法:hide
public function index()
{
$posts = Post::all();
return PostResource::collection($posts)->hide(['body']);
}
你应该得到一个没有 body 字段的帖子集合。