Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Zayar's avatar
Level 11

Scope Filter not working as expected

Hi, I need a little help. I have a User Model with belongsToMany(Role::class) and I have a Users table with options to filter the users by their role and also a Search Input where users can be searched by their name or email.

The bug is when a role is selected (i.e. customer) and all users of the selected role are displayed, if I type a name into the Search input, the selected role gets ignored and starts displaying users that match the search input, completely ignoring the role that was selected.

I believe the expected result should be to search for users within the selected role. I don't know what I im missing here.

User model:


public function roles()
{
	return $this->belongsToMany(Role::class);
}

public function scopeFilter($query, array $filters)
{
	$query->when($filters['search'] ?? null, function ($query, $search) use ($filters) {
		$query->where('name', 'like', "%{$search}%")
			->orWhere('first_name', 'like', "%{$search}%")
			->orWhere('last_name', 'like', "%{$search}%")
			->orWhere('email', 'like', "%{$search}%");
	})->when($filters['sortColumn'] ?? null, function ($query, $sortColumn) use ($filters) {
		$query->orderBy($sortColumn, $filters['sortDirection']);
	})->when($filters['option'] ?? null, function ($query, $option) {
		$query->whereHas('roles', function ($query) use ($option) {
			$query->where('role_id', '=', $option);
		});
	});
}
0 likes
4 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Whenever you have an orWhere, you always need to wrap that query in a function. It ensures that the query gets wrapped in ()

$query->when($filters['search'] ?? null, function ($query, $search) use ($filters) {
        $query->where(function ($q) { //here 
		  $q->where('name', 'like', "%{$search}%")
			->orWhere('first_name', 'like', "%{$search}%")
			->orWhere('last_name', 'like', "%{$search}%")
			->orWhere('email', 'like', "%{$search}%");
       });
	})->when($filters['sortColumn'] ?? null, function ($query, $sortColumn) use ($filters) {
		$query->orderBy($sortColumn, $filters['sortDirection']);
	})->when($filters['option'] ?? null, function ($query, $option) {
		$query->whereHas('roles', function ($query) use ($option) {
			$query->where('role_id', '=', $option);
		});
	});
1 like
Sinnbeck's avatar

@Zayar yeah it can be a bit hard the first time. But next time you see a orWhere, you know that you need to do something special

1 like
Zayar's avatar
Level 11

@Sinnbeck Definitely will keep that in mind. And thanks again for helping out.

Please or to participate in this conversation.