Answer the question
In order to leave comments, you need to log in
How to properly use resources in laravel?
There is a User model resource that has several specialties
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'specialities' => SpecialityResource::collection($this->activeSpecialities),
];
}
public function toArray($request)
{
return [
'user' => UserResource::make($this->user),
'special_price' => $this->special_price,
];
}
Answer the question
In order to leave comments, you need to log in
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'specialities' => SpecialityResource::collection($this->whenLoaded('activeSpecialities')),
];
}
public function toArray($request)
{
return [
'user' => UserResource::make($this->whenLoaded('user')),
'special_price' => $this->special_price,
];
}
You need to check for correlations. Well, the availability will depend on your request, if you call the with('user') request, then they will be displayed, if without that it will not be displayed, well, or you can still make different resources
So it's clearly written for you to run a mapper for child objects inside which to run a mapper for parent ones. Well, that's recursion for you, no?
Resource is array_map();
The collection() method is just array_map() for array_map().
Trying to make a resource for the user, you make a resource for the specialty inside, which then back makes a resource for the user.
It broke because you have a connection in both directions and you get a vicious circle (it is also called a graph). You need to make a door out of the graph, a sign by which your mapper understands that it was already there.
In addition, a little surprise - you are accessing the associated model, and since most likely you have not done with('specialitiesResource') before, then you have it also makes a request to the database in recursion
And the second surprise, even smaller, when you map a collection of users, then for each user it makes a request to the database for each specialty. Twice n+1 query in recursion
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question