Paul Lebedev
Paul Lebedev

Reputation: 103

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

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?

Upvotes: 8

Views: 16391

Answers (2)

frenus
frenus

Reputation: 501

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...

Upvotes: 11

Yosra Hamza
Yosra Hamza

Reputation: 559

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

Upvotes: 20

Related Questions