KordDEM
KordDEM

Reputation: 213

Laravel. How to return a links() pagination from the controller

I'm trying to return a pagination from the controller using the link function, but I return an empty value. What could be the problem?

$models= Model::with('table2', 'table3')
->simplePaginate(5);
$str= "";
foreach($models as model){
       $str .= model['name'];
}
return response()->json([
        'rows' => $str,
        'links' => $models->links()
    ], 200);

laravel 5.5

If I return

return $models->appends(['rows' => $str])->links();

I get what I want. But when you try to return an array or a json, the link is empty

Upvotes: 1

Views: 2258

Answers (2)

tringuyen
tringuyen

Reputation: 821

Use either the toArray or toJson methods, depending on what you need. For example::

$models = Model::with('table2', 'table3')->paginate(5)->toArray();
return [
    'models' => $models
];

Upvotes: 2

PPL
PPL

Reputation: 6555

When calling the simplePaginate method, you will receive an instance of Illuminate\Pagination\Paginator. These objects provide several methods that describe the result set. In addition to these helpers methods, the paginator instances are iterators and may be looped as an array. So, once you have retrieved the results, you may display the results and render the page links using Blade:

<div class="container">
    @foreach ($models as $user)
        {{ $user->name }}
    @endforeach
</div>

{{ $models->links() }}

Upvotes: 1

Related Questions