Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing data to api resource in request doesn't work in Laravel 8

Here’s my controller method:

public function getQrEntryCardsOfBranch(GetQrEntryCardsRequest $request)
    {
        $request->branch = $request->user()->branch();
        $qrEntryCards = $this->qrEntryCardService->getQrEntryCardsOfBranch($request->branch->id);
        return $this->apiResponse(Result::Success, __('messages.pacs.qrEntryCardsFetched'), QrEntryCardResource::collection($qrEntryCards), 200);
    }

And here’s my api resource class:

class QrEntryCardResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        $user = $this->user;
        return [
            'id' => $this->id,
            'title' => $this->title,
            'user' =>$user ? new SummaryUserResource($user) : null,
            'status' => $this->status,
            'createdAt' => Carbon::parse($this->created_at)->format(DateFormats::Ymd),
            'brandId' => $this->brand_id,
            'branchName' => $request->branch->name,
        ];
    }
}

I get an error because $request->branch is null.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I expect it to be not null, because I set it in Controller method.

I expect to be able to add data to $request and reach it from my api resource class but it’s not happening.

>Solution :

branch seted in controller. This request not passed to resource.

When a resource class is called in Laravel, the $request object passed to the toArray method of this class is created from the current HTTP request.

you can set branch on HTTP request like that

 request()->branch = $request->user()->branch();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading