We already know that how to use has() and whereHas() in laravel eloquent relational query. Now in this tutorial, I will show you how to use laravel wherehas multiple relations in a single query. Sometimes we need to use laravel nested wherehas in a single query. In this example I will show you use multiple wherehas in laravel eloquent query.

In this example, we will fetch posts with at least one inactive comment as well as at least one reply which comment_id less than 5. Let's see how we can write this query using laravel multiple wherehas.

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Database\Eloquent\Builder;

class TutorialController extends Controller
{   
    public function index()
    {   
        return Post::whereHas('comments', function(Builder $query){
                $query->where('is_approved', false) ;
            })
            ->whereHas('comments.replies', function(Builder $query){
                $query->where('comment_id', '<', 5) ;
            })
            ->get();
    }
}

 

Now see the output like that:

[
    {
        "id": 1,
        "user_id": 1,
        "title": "Maxime non architecto quia in corporis iusto odio beatae.",
        "is_published": 1,
        "created_at": "2023-01-15T04:59:18.000000Z",
        "updated_at": "2023-01-15T04:59:18.000000Z"
    }
]

 

Now see the whereHas with eager loading with method in laravel:

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\Project;

class TutorialController extends Controller
{   
    public function index(Request $request)
    {   
        $projects = Project::with([
                        'platforms.platform_name', 
                        'departments' =>  function($query) use($request){
                            return $query->whereIn('DepartmentCode',$request->SoftwareDepartment);
                        },
                        'developers.developer_name',
                        'departments.department_name'
                    ])
                    ->whereHas('departments',function($query) use ($request){
                        return $query->whereIn('DepartmentCode',$request->SoftwareDepartment);
                    })
                    ->get();
    }
}

 

Read also: Laravel WhereHas With Condition Example

 

Conclusion

Now we know laravel wherehas multiple relations. Hope this laravel nested wherehas in laravel tutorial will help you to create use multiple wherehas in laravel.