Laravel Case Study: How to Extend Paginate to Data Collection in Laravel

·

1 min read

Sometimes I have difficulty sorting data, for example, I want to sort data based on existing relationships with orderBy() and it doesn't work.

My alternative solution tried to utilize sortBy(), this only works for data collection types. I have to run the collection then I can use sortBy.

However, there are problems when we use collections, where collections do not have a paginate feature. In this tutorial, I will share how I added the paginate feature to a collection.

$stocks = Stock::query()
            ->with([ 'product'])
            ->search()
            ->when(@$request->product, function($query, $keyword) {
                return $query->whereHas('product', function ($query) use ($keyword) {
                        return $query->where('code', 'like', "%{$keyword}%");
                    });
            })
            ->get()
            ->sortBy(fn ($stock)  => return $stock->product->code; );

Lalu saya extend paginate di boot() pada provider AppServiceProvider

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

 public function boot()
    { 
 Collection::macro('CollectionPaginate', 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,
            ]);
        });
}

lalu untuk kita bisa menggunakan pagination seperti berikut:

   $stocks->CollectionPaginate(15);