A
A
Alexander Gamov2019-08-01 16:21:46
Laravel
Alexander Gamov, 2019-08-01 16:21:46

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),
    ];
}

Specialty resource that has a resource for the user.
public function toArray($request)
{
    return [
        'user' => UserResource::make($this->user),
        'special_price' => $this->special_price,
    ];
}

As a result, I get a recursion.
Somewhere I misunderstand the concept of resources, but I don’t understand what exactly.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Gamov, 2019-08-01
@slowdream

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,
    ];
}

K
Konstantin B., 2019-08-01
@Kostik_1993

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

G
Grigory Vasilkov, 2019-08-01
@gzhegow

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 question

Ask a Question

731 491 924 answers to any question