• info@drukhost.com

Laravel 4 comes equipped with a great pagination class which automatically generates a list of links for you which you can echo out directly in your view files. This default pagination works great if you just need simple pagination without using query strings.

But if you want to add your query strings to the generated pagination links, you will have to manually append the query strings to your links using the appends function.

This is not much of a problem if you only have few places where you want your query strings to be appended to the links. However, for some of us, we have a lot of places where we would want it generated automatically without having to append your query strings in all the controllers/views that you want to use it.

The two methods listed below is for Laravel 4, and may not work for earlier versions.

Method 1

You can make use of Laravel’s View Composers. These are methods that are called whenever a view is rendered. So whenever we are calling our views, we modify the Laravel’s paginator to include our query strings.

View::composer(Paginator::getViewName(), function($view) {
	$queryString = array_except(Input::query(), Paginator::getPageName());
	$view->paginator->appends($queryString);
});

Method 2

1. Open the file vendor\laravel\framework\src\Illuminate\Pagination\Paginator.php

2. On the top of the page, after the line

 use Illuminate\Support\Collection;

add the below line, which will tell the class to use the Input namespace, so you can call the Input class directly later.

use Input;

3. Now, go to the following function/method, and add the code in BOLD.

public function getUrl($page)
{
	$parameters = array(
		$this->env->getPageName() => $page,
	);
	$queryStrings = array_except( Input::query(), $this->env->getPageName() );
	$this->appends($queryStrings);
	if (count($this->query) > 0)
	{
		$parameters = array_merge($parameters, $this->query);
	}
	return $this->env->getCurrentUrl().'?'.http_build_query($parameters, null, '&');
}

What this does is, it appends the Input array to the links (except for the ‘page’, which will be inserted by default).

Now you can render your pagination links as usual, but all your query strings will be appended by default. This involves hacking your Laravel source files, and any changes may be lost if you update laravel in the future. But hopefully Laravel comes out with a better solution in its next update.

If you know of a better way to achieve this, please leave a comment.

Clients we have worked with