datarecall's avatar

Pagination

I have a method on my Supplier model that looks like:

public function getAllDiariesAttribute()
    {
        $products = $this->products();
        $weeks = $products->with('weeks.diary.latestWeek')->get()->pluck('weeks')->collapse()->pluck('diary');

        return $weeks->merge($products->with('diaries.latestWeek')->get()->pluck('diaries'))->flatten()->unique('id');
    }

Products are attached to the diary itself or to the weeks(which are attached to the diary)

Any thoughts on how you could make this an eloquent query to be able to do pagination on the results?

0 likes
4 replies
datarecall's avatar

@jlrdw the problem is I can't figure out how to turn that method into an eloquent query right now this is just a collection which you can't paginate cleanly

MichalOravec's avatar

When you add this macro to your AppServiceProvider

use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;

Collection::macro('paginate', function ($perPage, $total = null, $page = null, $pageName = 'page') {
    $page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);

    return new LengthAwarePaginator($this->forPage($page, $perPage), $total ?: $this->count(), $perPage, $page, [
        'path' => LengthAwarePaginator::resolveCurrentPath(),
        'pageName' => $pageName,
    ]);
});

Then you can paginate on the collection.

Please or to participate in this conversation.