Laravel whereHas and orWhereHas Query Example

Websolutionstuff | Jan-19-2021 | Categories : Laravel PHP MySQL

In this article, we will see the laravel whereHas and orWhereHas query example. whereHas and orWhereHas query is used in laravel for relationships. So, here I will give you an example of how to use whereHas in laravel 7, laravel 8, and laravel 9, whereHas eloquent in laravel 7/8 work the same as the has() function.

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation. whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

So, let's see the laravel 7/8/9 whereHas() and orWhereHas() query example and the whereHas() query example in laravel 7/8/9 or orWhereHas() query example in laravel 7/8/9.

Example 1:

$posts = Post::whereHas('comments', function (Builder $query) {
    $query->where('content', 'like', 'code%');
})->get();

 

Example 2:

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2021-01-01 00:00:00');
})->get();
// only users that have posts from 2021 on forward are returned

 

Example 3:

$posts = Post::whereHas('comments', function (Builder $query) {
    $query->where('content', 'like', 'code%');
}, '>=', 10)->get();

 

Example 4:

$posts = Post::has('comments', '>=', 3)->get();

 

Recommended Post
Featured Post
jQuery After And Before Example
jQuery After And Before Exampl...

In this article I will give you example of jquery after() and before() method. The after() method inserts spec...

Read More

Dec-10-2021

Autocomplete Search using Bootstrap Typeahead JS
Autocomplete Search using Boot...

In this example we will see autocomplete search using bootstrap typeahead js.Typeahead search is a method for progr...

Read More

Jun-09-2021

How To Create Unique Slug In Laravel 9
How To Create Unique Slug In L...

In this article, we will see how to create a unique slug in laravel 9. A slug is the part of a URL that i...

Read More

Sep-27-2022

Laravel 9 whereBetween Query Example
Laravel 9 whereBetween Query E...

In this article, we will see laravel 9 whereBetween query example. The whereBetween() method is used to check value...

Read More

Oct-14-2022