Reputation: 3
I'm working on a Friend Request Route.
Expected my code like following to work properly
$friends=[];
foreach (auth()->user()->friends as $friend)
$friends[]=$friend->id;
$people = User::query()
->where('id', '!=', auth()->user()->id)
->whereNotIn('id', $friends)
->where('name', 'LIKE', "%$request->search%")
->orWhere('email', 'LIKE', "%$request->search%")
->get();
But this code is working as
where ( 'id'!=auth()->user()->id and 'id' not in [...] and 'name' like '$name' ) or 'email' like '$email'
I expected this to work as
where 'id'!=auth()->user()->id and 'id' not in [...] and ('name' like '$name' or 'email' like '$email')
Than I changed my code to:
$friends=[];
foreach (auth()->user()->friends as $friend)
$friends[]=$friend->id;
$people = User::query()
->where('name', 'LIKE', "%$request->search%")
->where('id', '!=', auth()->user()->id)
->whereNotIn('id', $friends)
->orWhere('email', 'LIKE', "%$request->search%")
->where('id', '!=', auth()->user()->id)
->whereNotIn('id', $friends)
->get();
This is working for me but i do not think it proper. Kindly Guide.
Upvotes: 0
Views: 1001
Reputation: 9029
You may use "Parameter Grouping" like this:
$people = User::query()
->where('id', '!=', auth()->user()->id)
->whereNotIn('id', $friends)
->where(function ($query) use ($request) {
$query->where('name', 'LIKE', "%$request->search%")
->orWhere('email', 'LIKE', "%$request->search%");
})
->get();
As you can see, passing a
Closure
into thewhere
method instructs the query builder to begin a constraint group. TheClosure
will receive a query builder instance which you can use to set the constraints that should be contained within the parenthesis group.
See Laravel docs for more info.
Upvotes: 2
Reputation: 467
You need to use query for this.
It's something like this :
For more information, you can check this Documentation
$people = User::query()
->where('id', '!=', auth()->user()->id)
->whereNotIn('id', $friends)
->where(function ($query) {
$query->where('name', 'LIKE', "%$request->search%")
->orWhere('email', 'LIKE', "%$request->search%")
})->get();
Upvotes: 0