D
D
dmalapsh2021-08-21 02:32:37
Laravel
dmalapsh, 2021-08-21 02:32:37

How to control automatic model loading in laravel controller method?

Using the artisan command, I created a controller bound to the Announcement model. In the same place I found a very interesting code of the following type.

public function show(Announcement $announcement)
    {
    	/****/
    }

That is, laravel itself injects a ready-made model, knowing by url with what id it is necessary to request from the database.
And everything would be fine, but I did not find information about this in the documentation. I thought that I would find the answer in the section about service containers, but the search was unsuccessful. The bottom line is that I need to load the relation when loading the model in this way, but I don’t know where to go with this. Of course, you can use load instead of with, but I would like to organize this in one request to the database, and not write extra code in the method.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2021-08-21
@dmalapsh

In the context of a single model, rather than a collection, load works exactly the same as with - it makes a second query to the relationship table.
So you can even not call load, but simply use a relation - Eloquent will automatically load everything. Load is needed here only if you need to control the loading of the relation: specify an additional condition or additional links.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question