Duddy67
Duddy67

Reputation: 1046

Laravel collection AND WHERE clause

I'm a bit confused regarding the AND WHERE clause whith collections.
The following query gets all the users owning a car licence OR a motorbike licence:

User::whereHas('licences', function($query) {
    $query->whereIn('type', ['car', 'motorbike']);
})->get();

Now how to get all the users owning a car licence AND a motorbike licence ?

Upvotes: 0

Views: 124

Answers (3)

OMR
OMR

Reputation: 12188

try duplication your whereHas:

$wantedLicences= ['car', 'motorbike'];
$query=User::query();

foreach($wantedLicences as $wantedLicence)
{
    $query=$query->whereHas('licences', function($query)use($wantedLicence) {
        $query->where('type', $wantedLicence);
    })
}
  

Upvotes: 1

lagbox
lagbox

Reputation: 50481

Assuming a User can't have more than one type of a license then you would adjust the whereHas to check that the count of related records equals 2:

User::whereHas('licenses', function ($query) {
    $query->whereIn('type', ['car', 'motorbike']);
}, '=', 2)->get();

Laravel 8.x Docs - Eloquent - Relationships - Querying Relationship Existence

Upvotes: 2

ashok poudel
ashok poudel

Reputation: 723

The query should be like this for getting users owning a car and a motorcycle

User::whereHas('licences', function($query) {
       $query->where('type','car')->where('type','motorbike');
})->get();

Upvotes: -1

Related Questions