Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Paginate Not Working with ::where(...)

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()

like image 884
Tim Lewis Avatar asked Mar 26 '15 20:03

Tim Lewis


2 Answers

Try like this '%'.$search.'%'

$templates = Template::where($field, "LIKE", '%'.$search.'%')
    ->orderBy($sort, $order)
    ->paginate(100); 
like image 160
Alupotha Avatar answered Nov 18 '22 19:11

Alupotha


I found out the solution this morning, seems I needed to sleep the issue off. Basically, when I called the search method, along with $_GETing 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.

like image 2
Tim Lewis Avatar answered Nov 18 '22 19:11

Tim Lewis