Laravel provides with() method for eager loading relationships and also provides whereHas() to check relational data existence with conditions. We can use it in our eloquent single relational query. So in this tutorial, I will show you eager loading with wherehas conditions in laravel. I will show you the example code of eager loading with wherehas example in laravel.

I will use Post and Comment model to create this laravel 9 eager loading with wherehas conditions query. But this code will work with any laravel version which is bigger than version 5. 

laravel-eager-loading-with-wherehas-example

Now let's see the example code of laravel 9 eager loading with wherehas conditions:

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

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

class TutorialController extends Controller
{   
    public function index(Request $request)
    {   
        return Post::with([
                    'platforms.platform_name', 
                    'departments' =>  function($query) use($request){
                        return $query->whereIn('code',$request->code);
                    },
                    'developers.developer_name',
                    'departments.department_name'
                ])
                ->whereHas('comments', function(Builder $query){
                    $query->where('is_approved', false) ;
                })
                ->whereHas('comments.replies', function(Builder $query){
                    $query->where('comment_id', '<', 5) ;
                })
                ->get();
    }
}

 

Read also: Laravel WhereHas Multiple Relations Example

 

Conclusion

Now we know eager loading with wherehas conditions in laravel. Hope this eager loading with wherehas example in laravel tutorial will help you to create laravel 9 eager loading with wherehas conditions.