Laravel Framework, PHP & MySQL, Tutorials

When using Laravel's ORM in a standalone project you'll want to use pagination, my first though is to use the pagination class but this is tighly coupled into Laravel meaning you cannot use it outside of Laravel.

My next though was can I use a standalone pagination class I wrote https://github.com/daveismyname/pagination

I needed to add another method to this called get_limit_keys that retuns the offset and limit values back so I can then take those values and use ->offset(0) and ->take(50) in laravel, whilst that worked I was doing a lot of manual processing that if I extended the pagination class I can get the class to do it for me.

I created a class called LaravelPaginator that extends from the paginator class

class LaravelPaginator extends Paginator

Next created a method called paginate that expects an ORM object to be passed:

public function paginate($object)

Now I can set the set_total() call insie this method so I never need to do it manually again. Since I'm passing a ORM object I can end it with ->count() to return the number of records within.

$this->set_total($object->count());

Next I want to return the object and call offset and take:

return $object
			->offset($this->get_limit_keys()['offset'])
			->take($this->get_limit_keys()['limit'])
			->get();

the Completed class looks like this:

class LaravelPaginator extends Paginator
{
	public function paginate($object)
	{
		$this->set_total($object->count());

		return $object
			->offset($this->get_limit_keys()['offset'])
			->take($this->get_limit_keys()['limit'])
			->get();
	}

}

Usage:

//create an instance of the object but don't execute it ie leave off ->get()
$records = Ticket::orderby('subject');

//create a new instance of the new class, set the perPage limit to be 5 and the seperator to be ? this will create links like ?p=2
$pages = new LaravelPaginator('5','p');

//get the records back from the object
$rows = $pages->paginate($records);

//get the page links
$links = $pages->page_links();

Now you can paginate over the $rows and use $links to show the page links!

Optionally you can pass $_GET params from page to page, here is an automated way of doing it:

function remove_querystring($key) { 
	$url = preg_replace('/(.*)(\?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $_SERVER["QUERY_STRING"] . '&'); 
	$url = substr($url, 0, -1);
	return $url; 
}

//call remove_querystring and pass in the name of the $_GET request to be removed
$querystring = remove_querystring('p');

//call page_links and set the seperator to be ? and the $querystring
$links = $pages->page_links('?', $querystring);