Eloise85
Eloise85

Reputation: 676

Laravel Eloquent search inside related table

I'm having a list of users which have multiple roles and Iwish that my ajax search method could search inside this resultset (user1 have user role and admin role). So Iwrote my request like this :

$usersData = User::where('name', 'like', $queryString . '%')
        ->orWhere('email', 'like', $queryString . '%')
        ->orWhere('username', 'like', $queryString . '%')
        ->when($limit > 0 || $offset > 0, function ($usersData) use ($limit, $offset) {
            $usersData->take($limit)->skip($offset);
        })
        ->with('roles:name')->whereHas('roles',function($query) use($queryString){
            $query->where('roles.name','like',$queryString.'%');
        })
        ->get();

But it doesn't work have you an idea what is the problem ? Thanks.

Upvotes: 3

Views: 1413

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163968

Use orWhereHas() instead of whereHas():

->orWhereHas('roles', function($query) use($queryString){
    $query->where('name', 'like', '%' . $queryString. '%');
})

Upvotes: 3

Related Questions