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.
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();