Have you tried moving ->paginate(5); around to a different location in the code or tested with one of the name of email only?
Jan 14, 2017
6
Level 1
Laravel 5.3 Pagination With Query Builder Problem [Solved]
the following code:
$data = User::orWhere(function($query) use ($request){
if ($name = $request->input("name")) {
$query->orWhere("name", 'LIKE', '%'.$name.'%');
}
if ($email = $request->input("email")) {
$query->orWhere("email", 'LIKE', '%'.$email.'%');
}
if($roles = !empty($request->input('roles'))) {
$query->orWhereHas('roles', function ($query) use ($request) {
$roles = implode(",",$request->input('roles'));
$query->whereIn('role_id', [$roles]);
});
}
})
->paginate(5);
is producing the result:
Array
(
[0] => Array
(
[query] => select count(*) as aggregate from `users` where (`name` LIKE ? or exists (select * from `roles` inner join `role_user` on `roles`.`id` = `role_user`.`role_id` where `role_user`.`user_id` = `users`.`id` and `role_id` in (?)))
[bindings] => Array
(
[0] => %string%
[1] => 1,2
)
[time] => 0.95
)
[1] => Array
(
[query] => select * from `users` where (`name` LIKE ? or exists (select * from `roles` inner join `role_user` on `roles`.`id` = `role_user`.`role_id` where `role_user`.`user_id` = `users`.`id` and `role_id` in (?))) limit 5 offset 0
[bindings] => Array
(
[0] => %string%
[1] => 1,2
)
[time] => 0.46
)
)
and the result given to blade isnt right. what im doing wrong? how to fix it?
Level 50
@Hikaro maybe something like this would be better... haven't tested it though..
$data = User::when(request()->has('name'), function($query) {
$query->orWhere('name', 'LIKE', '%' . request('name') . '%');
})->when(request()->has('email'), function($query) {
$query->orWhere('email', 'LIKE', '%' . request('email') . '%');
})->when(request()->has('roles'), function($query) {
$query->orWhereHas('roles', function($query2) {
$query2->whereIn('role_id', request('roles'));
});
})->paginate(5);
2 likes
Please or to participate in this conversation.