Abhijit Mondal Abhi
Abhijit Mondal Abhi

Reputation: 1899

Can not use where clause after using with clause in Laravel query

I am writing a query using with and then where clause in laravel.

 $users = User::query()->with('roles')->where('name', '!=', 'customer')->get();
 return $users;

But where clause is not working here. Customers are not excluded. I am providing the snap shot of the query result.

enter image description here

Upvotes: 1

Views: 522

Answers (2)

STA
STA

Reputation: 34838

I think you need whereHas() :

use Illuminate\Database\Eloquent\Builder;

$users = User::query()
          ->with('roles')
          ->whereHas('roles', function (Builder $query) {
                $query->where('name', '!=', 'customer');
          })
      ->get();

return $users;

Upvotes: 4

Artem Tumanov
Artem Tumanov

Reputation: 102

I suppose you trying to filter relation data in base query. Try smth like that:

$users = User::query()->with([
  'roles' => function ($q) {
      $q->where('name', '!=', 'customer');
    }])
  ->get();

return $users;

Doc

Upvotes: 1

Related Questions