Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set count items per page by default in Laravel 5 paginate

Tags:

laravel-5

In Laravel 5 if i use Something::paginate() i will get 15 items per page. Course i can do anytimeSomething::paginate(20).

But how to override default count and use value from my .env?

like image 545
Paul Lebedev Avatar asked Jun 09 '16 07:06

Paul Lebedev


2 Answers

You can override the $perPage variable in your model by putting

   protected $perPage = 10;

inside your model that overrides the $perPage=15 original variable defined in Model.php

like image 144
Yosra Hamza Avatar answered Oct 28 '22 09:10

Yosra Hamza


The question was asked ages ago, but if anyone needs a way to do it, you can just use a trait in your model. I had to get the per_page from the request to accept a 'all' and return all the records, with a max that can't go over.

<?php

namespace App\Traits;

trait Paginatable
{
    protected $perPageMax = 1000;

    /**
     * Get the number of models to return per page.
     *
     * @return int
     */
    public function getPerPage(): int
    {
        $perPage = request('per_page', $this->perPage);

        if ($perPage === 'all') {
            $perPage = $this->count();
        }

        return max(1, min($this->perPageMax, (int) $perPage));       
    }

    /**
     * @param int $perPageMax
     */
    public function setPerPageMax(int $perPageMax): void
    {
        $this->perPageMax = $perPageMax;
    }
}

Hope it helps...

like image 34
frenus Avatar answered Oct 28 '22 11:10

frenus