Laravel WhereHas Eloquent with condition Example

Today, We want to share with you wherehas in laravel.In this post we will show you how to use orwherehas in laravel?, hear for Using WhereHas in Laravel Polymorphic Relations we will give you demo and example for implement.In this post, we will learn about Laravel 6 Eloquent Has With And WhereHas with an example.

Laravel – Eloquent “Has”, “With”, “WhereHas”

How to use whereHas with orWhereHas in Laravel?

public function myMembers()
    $members = Member::with(['location', 'area']);
    if ($request->has('name')) {
         $members = $members->whereHas('location', function( $query ) use ( $request ){
                      $query->where('name', $request->name);
                  })->orWhereHas('area', function( $query ) use ( $request ){
                      $query->where('name', $request->name);
    $members = $members->get();

Laravel with() eloquent method

Member > hasMany > Article

$members = Member::with('articles')->get();
foreach($members as $member){
    $members->articles; // articles is already loaded and no additional DB query is run

using Has

Laravel eloquent has() method
Member > hasMany > Article

$members = Member::has('articles')->get();
// only members that have at least one post are contained in the collection

using WhereHas

Laravel eloquent whereHas() method (Member > hasMany > Article)

$members = Member::whereHas('articles', function($q){
    $q->where('created_at', '>=', '2021-01-01 00:00:00');
// only members that have articles from 2021 on forward are returned

I hope you get an idea about how to use whereHas and orWhereHas in laravel 6, laravel 7 and laravel 8 application..
I would like to have feedback on my blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment