In a project familiar with lists and numbering, you should have the option to choose, how many entries you want to see per page – 10, 25, 50, 100 etc. The setting may refresh the schedule or the entire page, but how to save that for the next time a user logs in, or visits a page in a week?

When users click one of page entries, they are redirected to the “URL: /posts?per_page=XXX“, where the “XXX” may represent one of those options – 25, 50, or 100.

Pretty simple, right? But then if user goes away and comes back in a day, or a week, they probably would love that setting to stay for them, so they wouldn’t need to click that number again. So where to save it?

In PostController.php you probably have something like this:

$posts = Post::where('some_conditions', $some_variables)
  ->paginate($posts_per_page);

Now, the question is how to get that $posts_per_page so it would come not only from GET Request variable but from your history?

There are two ways: first, you can save it in users DB table – add one field, and update the value there. But what if you don’t have any user system, and the list is public? Then you need to use Cookies.

Here’s the code to get that $posts_per_page from Cookies, or GET request.

$cookie_value = Cookie::get('posts_per_page');
$posts_per_page = $request->get('posts_per_page', $cookie_value);

$options = config('constants.posts_per_page_options');
if (!$posts_per_page || !in_array($posts_per_page, $options)) {
    $posts_per_page = config('constants.posts_per_page_default');
}

Cookie::queue('posts_per_page', $posts_per_page);

Break down the code to two blocks.

First block:
$cookie_value = Cookie::get('posts_per_page');
$posts_per_page = $request->get('posts_per_page', $cookie_value);

The codes means that let’s try to get posts_per_page from GET request, if it’s not there, then let’s default to the data in the Cookie.

But what if there’s no Cookie? That’s the second block:

Second block:
$options = config('constants.posts_per_page_options');
if (!$posts_per_page || !in_array($posts_per_page, $options)) {
    $posts_per_page = config('constants.posts_per_page_default');
}

We save possible pagination values, and a default value in config file – in my case it’s config/constants.php:

return [
    'posts_per_page_options' => [25, 50, 100],
    'posts_per_page_default' => 25,
];

In that case, we’re checking if the value is not set in GET Request or Cookie or if it’s other than possible from config – then we default to the 25 per page.

Finally, last line is just saving that value into the Cookie again for the future requests.

Credit to: https://bit.ly/3J1mbRc