Skip to content
CakePHP

Using Query Strings with the CakePHP Paginator

2 min read

CakePHP's paginator pretty much just works. However, if you find yourself with the edge case of having to use a query string with it you'll find yourself coming unstuck. The paginator doesn't know about the query string. It is relatively simple to tell it about the query string though.

In the view where you are paginating with a query string (CakePHP 2.0+) we just need to set the paginator's URL option:-

$this->Paginator->options(
    array(
        'url' => array_merge(
            $this->passedArgs,
            array(
                '?' => ltrim(strstr($_SERVER['QUERY_STRING'], '&'), '&')
            )
        )
    ) 
);

In the above code we are ensuring that the parameters for the current action are being preserved by using passedArgs and merging these with the query string. The manipulation to the server's query string using ltrim and strstr is to ensure that the url variable that CakePHP uses behind the scenes is discarded as we don't need it here.

If you're using CakePHP 1.3+ you'll need to use:-

$paginator->options(
    array(
        'url' => array_merge(
            $this->passedArgs,
            array(
                '?' => ltrim(strstr($_SERVER['QUERY_STRING'], '&'), '&')
            )
        ) 
    )
);

It's a shame that CakePHP's paginator doesn't work with the query string by default, but this tweak should fix things should you find yourself needing to use the it.

© 2024 Andy Carter