1

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

2
  • 2
    where() clause is working here for your users table, not for the roles table Commented Feb 1, 2021 at 15:11
  • 1
    The where is only on the User query, not the Roles query. If you want it on the roles query, you'll need to pass it in as a closure. laravel.com/docs/8.x/… Commented Feb 1, 2021 at 15:11

2 Answers 2

4

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; 
Sign up to request clarification or add additional context in comments.

2 Comments

One question why we are using Builder before the query. Without declaring Builder it also works fine. @sta
@AbhijitMondalAbhi It's called type hinting. Object of class/interface is forced so no other object types can be provided. Safety measure. Also, query()-> can be skipped.
1

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

1 Comment

This is excluding customers. But, it returns all Users which doesn't have the roll customer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.