Advanced query for eager loaded relations in Laravel’s Eloquent

Laravel's relations is really nice, but the Eloquent does not load the relations automatic.

There are many ways to load the relations, but if you really want to reduce queries to the database, then you have to use the eager loading functionality. This will reduce the number of queries drastically.

It could look something like this:

$users = User::with('comments')->orderBy('username', 'desc')->limit(10)->get();

This will load 10 users, ordered by username desc, and all their comments, if the relations is set up the right way in the models.

But if we want more advanced queries for the relations, we can do something different:

$users = User::with(array(
   'comments' => function($query) {
      $query->where('likes', '>', 10)->orderBy('date', 'asc');
))->orderBy('username', 'desc')->limit(10)->get();

This will do the same as the above, except it will only load comments that has more than 10 likes, and order the comments by date asc.

This is a really useful feature. You can see more in this post:'

Martin Schadegg Rasch Jensen