J
J
jazzus2019-05-20 13:23:30
Laravel
jazzus, 2019-05-20 13:23:30

How to pass variable to Laravel Resource Collection?

In the controller I do a check and give the collection in json

$check =  проверка с запросом в бд возвращает true/false;
return ProjectResource::collection($projects);

in the resource, the field is formed from the method . If you do a check in the metod method, then there will be a request to the database for each object of the collection (because check makes a request to the database). Therefore, it is necessary to transfer the result of the check to the resource in advance, i.e. check variable. How can I do this without transforming the collection with map in the controller? Is it possible to pass a variable to a resource?
'check' => $this->metod($check),

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex Wells, 2019-05-20
@jazzus

To the base class of the collection

/**
     * Create new anonymous resource collection.
     *
     * @param mixed         $resource
     * @param callable|null $each
     *
     * @return AnonymousResourceCollection
     */
    public static function collection($resource, callable $each = null)
    {
        $collection = new AnonymousResourceCollection($resource, \get_called_class());

        if ($resource && (! $resource instanceof MissingValue) && $each) {
            $collection->resource->each($each);
        }

        return $collection;
    }

and into the controller
$check = true;

return ProjectResource::collection($projects, function (ProjectResource $resource) use ($check) {
    $resource->setCheck($check);
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question