Hello Laravel Lover
In this tips tutorial i am going to discuss about laravel whereHas and doesntHave query example. Sometimes we face such type of situation that you want to fetch only such kind of data that has atleast one product. In this tutorial i will show you how we can fetch supplier and category that has at least one product.
Laravel whereHas and doesntHave is very important eloquent method which reduces our query. Those above methods allow you to add customized constraints to a relationship constraint, such as checking the below example.
Laravel whereHas Query Example
$supplier = \App\Supplier::whereHas('products', function (Builder $query) {
$query->where('is_active',1);
})->get();
Here we fetched all the supplier which has at least one product. See another example.
$category = \App\Category::whereHas('products', function (Builder $query) {
$query->where('is_active',1);
})->get();
Here we fetched all the categories which has at least one product. See the below code to know how to use multiple whereHas in Laravel
Category::whereHas('products', function($query) {
$query->where('is_active','1')->where('price', '>', 1000);
})->get();
When you want to access the records for a model, you may wish to limit your results based on the absence of a relationship. For example, imagine you want to retrieve all blog posts that don't have any comments.
For doing that you may pass the name of the relationship to the doesntHave
and orDoesntHave
methods:
Laravel doesntHave Query Example
$posts = App\Post::doesntHave('comments')->get();
If you need even more power, you may use the whereDoesntHave
and orWhereDoesntHave
methods to put "where" conditions on your doesntHave
queries.
use Illuminate\Database\Eloquent\Builder;
$posts = App\Models\Post::whereDoesntHave('comments', function (Builder $query) {
$query->where('is_active', 1);
})->get();
Read also : Laravel whereJsonContains Query Example
Hope this Laravel eloquent tips tutorial will help you.
#laravel #laravel-8x #eloquent-tips