Where condition in Laravel Relationship

Posted by


In Laravel, you can use the where condition on relationships to retrieve related models that meet specific criteria. Here’s an example of how to use the where condition in Laravel relationships:

Several days ago i had same situation when i used laravel relationship. need to use where condition like i need to get those users that country is “India“. so i write condition like as 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:

$search = 'India';

  

$users = User::whereHas('countries', function($q) use($search){

    $q->where('name', '=', $search);

})->get();

  

dd($users);

It can help you!!!

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x