Where condition in Query Builder Laravel Relationship Example

BOOKC, this time share about Where condition in Query Builder Laravel Relationship Example

Laravel 5 provides great features as a relationship model. but if you need to use where clause in your relational model then how can you do it?, you can create where condition using whereHas function. it doesn't matter which relation you use like one to one, one to many, many to many, have many through etc.

Sometimes maybe you need to add condition where with your relation model then you can just use whereHas() as I give an example below with laravel 6, laravel 7, laravel 8 and laravel 9 applications.

A few days ago I ran into the same situation when I was using laravel relations. need to use a condition where I need to get a user whose country is "India". so i write condition like below example:

Example:

$users = User::whereHas('countries', function($q){
    $q->where('name', '=', 'India');
})->get();
dd($users);

You can also pass dynamic variable inside the whereHas() like this way:

Example 2:

$search = 'Indonesia';
$users = User::whereHas('countries', function($q) use($search){
    $q->where('name', '=', $search);
})->get();
dd($users);
so many articles about Where condition in Query Builder Laravel Relationship Example may be useful
Bookc
Admin

Hopefully the information we provide can be useful.

Press ESC to close