I'm having an issue with Laravel's ->paginate()
method. Basically, I have a dynamic query that, based on the GET
parameters passed to the controller, has or does not have a ::where()
clause in it. Without the ::where()
, I can call ->paginate(100)
and split the result set into pages of 100. When trying to do the same thing with ::where(...)->paginate(100)
I get 0 results.
At first I thought my query was wrong, but removing the ->paginate(100)
and replacing it with ->get()
returns the expected number of results. Here is the complete code:
$search = ((Input::get("search") != "") ? Input::get("search"):"");
$field = ((Input::get("field") != "") ? Input::get("field"):"");
if($search != "" && $field != ""){
$templates = Template::where($field, "LIKE", $search)
->orderBy($sort, $order)
->paginate(100); // Fails (0 Results)
->get(); // Works (3 Results)
} else {
$templates = Template::orderBy($sort, $order)
->paginate(100);
}
I'm not sure why ->paginate()
is returning 0 results. Also, dd($templates)
returns the entire object(Illuminate\Pagination\Paginator)
collection, which has my results, but not in an accessible way. If you want to see the result I'm talking about, run dd()
on a query without ->get(), ->first() or ->paginate()
Try like this '%'.$search.'%'
$templates = Template::where($field, "LIKE", '%'.$search.'%')
->orderBy($sort, $order)
->paginate(100);
I found out the solution this morning, seems I needed to sleep the issue off. Basically, when I called the search method, along with $_GET
ing the field=example&search=test
, it would also send the current page, for example page=2
. Now, if the result set returned < 100 results, page 2 wouldn't exist, and no results would be returned (because of limit 100 offset 100
) in the query. Making the search function $_GET
the base URL without the page properly linked to page=1
and showed the results I was expecting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With