我在一个博客项目中。我的Post模型有这个API资源
return [
'id' => $this->id,
'title' => $this->title,
'body' => $this->body,
'date' => $this->date
];
但是我不希望在收到帖子集时得到'body' => $this->body
,因为我只在我要显示帖子时才使用它,而不是列出它们
我该怎么做?我应该使用资源集合吗?
更新:
makeHidden
应该可以,但不是因为我们有Illuminate\Support\Collection
而不是Illuminate\Database\Eloquent\Collection
,我该如何进行强制转换或使API资源的collection方法返回Illuminate\Database\Eloquent\Collection
实例?
答案 0 :(得分:0)
我假设您有一个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']);
}
您应该获得没有正文字段的帖子集合。
答案 1 :(得分:0)
There is a method for conditionally adding attribute to resource as shown below
return [
'attribute' => $this->when(Auth::user()->isAdmin(), 'attribute-value'),
];
I hope this will help you.