使用Laravel API资源时如何删除集合中的某些值

时间:2019-12-05 17:38:37

标签: laravel eloquent laravel-6 laravel-eloquent-resource laravel-api

我在一个博客项目中。我的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实例?

2 个答案:

答案 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.