4
votes

I am building a dynamic query using eloquent based on user inputs.

$query = \App\Model::query();
if($this == request('that')){
    $query->where(...); // building dynamic query based on user inputs
}

and finally user can type number of records shown per page in an html input field named count or checking a checkbox input type named all and following code completes dynamic query in back-end:

if (request('all')) {
    $result = $query->get();
}else {
    $result = $query->paginate(request('count'));
}

Also in front-end I have following code to show pagination links:

{{$result->links()}}

The problem is when user chooses to show all records we face following error:

Method links does not exist.

links method is not callable when we retrieve objects via get() method. What is the best practice in order not to face this error?

1

1 Answers

8
votes

It's because ->get() method return collection instead of paginator model Illuminate\Pagination\LengthAwarePaginator. So I can recomment you send some addition variable from your controller which indicate if you need execute $result->links().
Controller:

return view('yourView', [showPagination => is_null(request('all'))]);

View:

@if($showPagination)
   {{$result->links()}}
@endif