In this tutorial you will learn about the Laravel WhereHas Eloquent Example and its application with practical example.
In this Laravel WhereHas Eloquent Example tutorial, we will learn about laravel eloquent whereHas() method with the example. In this tutorial we will also learn about laravel has() and with() eloquent methods.
Laravel Eloquent With Method
The Laravel with()
method represent eager loading. The laravel with method preload the relationship(s) you specify along the main model. This is helpful when you have a collection of models and you want to load a relation for all of them. With eager loading you run only one additional DB query instead of one for every db model.
Example:-
User > hasMany > Post
1 2 3 4 |
$users = User::with('posts')->get(); foreach($users as $user){ $users->posts; // posts is already loaded and no additional DB query is run } |
Laravel Eloquent has Meth
od
The eloquent has()
method in laravel is used to filter the selecting model based on the selected relationship provided. It works like where
method in laravel.
Example:-
User > hasMany > Post
1 2 |
$users = User::has('posts')->get(); // only users that have at least one post are contained in the collection |
Laravel Eloquent WhereHas Method
The eloquent whereHas() method in laravel works like the has() method but it just allows you to specify some additional filters for related laravel model to check in laravel.
Example:-
User > hasMany > Post
1 2 3 4 |
$users = User::whereHas('posts', function($q){ $q->where('created_at', '>=', '2020-01-01 00:00:00'); })->get(); // only users that have posts from 2020 on forward are returned |