In this tutorial, we will see laravel whereHas and orWhereHas query example. whereHas and orWhereHas query used in laravel for relationships. So, here I will give you an example of 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.

So, let's see the laravel whereHas and orWhereHas query example, Also you can use whereHas and orWhereHas in laravel 6, laravel 7, and laravel 8.

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

You might also like :

  • Read Also: Laravel whereIn and whereNotIn Query Example

  • Read Also: Laravel 8 Database Seeder Example

  • Read Also: CRUD Operation In PHP

Logo

华为、百度、京东云现已入驻,来创建你的专属开发者社区吧!

更多推荐