DEV Community

loading...

Laravel whereHas and orWhereHas Query Example

Websolutionstuff
I am Laravel Developer. I have good knowledge of JavaScript, JQuery, Bootstrap and REST API.
Originally published at websolutionstuff.com ・1 min read

Hello Friend,

In this tutorial i will post laravel whereHas and orWhereHas query example, wherehas and orWhereHas query used in laravel for relationships.

So, here i will give you example how to use wherehas in laravel, wherehas eloquent in laravel 8 work same as 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.

Example 1 :

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

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
Enter fullscreen mode Exit fullscreen mode

Read Also : How To Create Dynamic Pie Chart In Laravel 8

Read Also : How To Check Email Already Exist Or Not In Laravel

Thanks for the reading...!!
Don't forgot to like, share and comments.

Discussion (0)