In the official documentation for Laravel there is an example where we can set additional parameters when loading relations, through a lazy download.

Here is an example

$users = App\User::with(['posts' => function ($query) { $query->select('id', 'login'); }])->get();

How can I do the same for nested relationships? Suppose I need fields only the name of the book, the date of writing, and the surname of the author.

 $users = App\User::with(['book.author'])->get(); 
  • While I did it in the following way, I don’t know how correct it is, mb who will tell you a shorter way. `$ users = App \ User :: with (['book' => function ($ query) {$ query-> select ('name', 'create_date');} 'book.author' => function ($ query ) {$ query-> select ('fio');}]) -> get (); ` - David

1 answer 1

It is quite possible to use your answer in the comment, it is possible to facilitate the use in the controller if you create a new connection in the model itself, following the example already written

 public function bookCut() { return $this->hasMany(Параметры связи)->select(['id', 'name', 'create_date']); } public function authorCut() { return $this->hasMany(Параметры связи)->select(['id','fio']); } 

And then use this:

 $users = App\User::with(['bookCut.authorCut'])->get(); 

In select, you need to add the required fields to your output and fields for the connection to work (id, for example)

  • Thank you) I did not know that it was possible) - David