E
E
Eugene-Kei2020-07-19 14:26:18
Laravel
Eugene-Kei, 2020-07-19 14:26:18

How to load links in laravel resource collection in one request?

I want to make it possible for the api to specify some connections in the get parameter that the client may need.
For example, when receiving posts, indicate that the authors of these posts are also needed.
Initially, this was only needed for a list of resources ala get / posts. I made a separate filtering class through which Post::query() is run and, depending on the get parameters in the Request object, selection, sorting, and external relations conditions are added to the request. In general, it works fine.
Then there was a need to receive links when receiving one, specific resource (get /posts/123).
The show method of the controller immediately receives the finished model of the desired post, if any.

class PostController  extends Controller
{
    public function index(Request $reqquest)
    {
        //...
    }

    public function show(Request $request, Post $post)
    {
        //...
    }
}

If, in the case of the index method, I work with \Illuminate\Database\Eloquent\Builder and add conditions for selecting links to it, then in the case of the show method, I already have a ready-made model and need to work with it.

I want to make one handler that will determine which links are needed and use it in all cases. Looked JsonResource. For a single post, you can add connection connections if necessary. But if we do this for a collection of 50 - 100 posts, then we get 50 - 100 additional queries to the database. If it were possible to load relationships with one request for the entire collection of child classes JsonResource, then it would be convenient. I would not add links to the Builder, but would only use resources.

Actually, are there any built-in gadgets for this in the stall? So that bicycles do not fence.
Or maybe there are some more reasonable approaches that I don't see? I have recently studied Lara, I don’t know much yet.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2020-07-20
@jazzus

In the controller

public function show(Post $post)
{
  $post->load('relations');
   ...
}

In resource
'relations' => RelationResource::collection($this->relations)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question