Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pagination in laravel 5 producing wrong link

When creating pagination on users page the pagination links are not right they are with / before page=1 so the link redirect to root with 404 not found.

Controller method:

public function getRegister()
{
    $users = User::where("admin", 0)->paginate(3);

    return view('auth.register', compact('users'));
} 

view

<?php echo $users->render(); ?>

users page url: http://localhost:8080/pal/public/agent/create

pagination links:http://localhost:8080/pal/public/agent/create/?page=1

when click on paging link browser redirect me to: http://localhost:8080/agent/create?page=3 and got 404 page NOT FOUND

like image 993
Ayman Hussein Avatar asked Apr 23 '15 21:04

Ayman Hussein


2 Answers

Unfortunately, that's, at least for now, how Laravel 5 works.

To get rid of that additional slash, you have to manually handle pagination links before rendering them.

You can either: 1) in your controller, call setPath() on the paginator instance, like this:

public function getRegister()
{
    $users = User::where('admin',0)->paginate(3);
    $users->setPath('your/custom/path');
    return view('your/view')->with('users',$users);
}

Next in your view, simply call render() and it should work as expected.

or 2) modify nothing in controller but change link format in your view, for example:

{!! str_replace('/?', '?', $users->render()) !!}

You may refer to the question I raised before.

Hope this helps!


I am still looking for more elegant solution but have not got any yet :(


Updated on 2016-05-30

Thanks for all the up-votes. Please note that in Laravel 5.2, you don't have to hack the code in a way mentioned above any more! Calling render() in views is all that you need to do. That's great, isn't it?

like image 69
Carter Avatar answered Nov 01 '22 05:11

Carter


I like carter's answer, I prefer the first suggestion which is using setPath. Setting "setPath" to an empty string worked for me. :)

$users->setPath('');
like image 23
Wreeecks Avatar answered Nov 01 '22 06:11

Wreeecks