How can I paginate a merged collection in Laravel 5?

后端 未结 7 1510
温柔的废话
温柔的废话 2020-12-02 14:31

I am creating a stream which contains two types of objects, BluePerson and RedPerson. To create the stream, I fetch all of both objects, then merge them into one collection.

7条回答
  •  独厮守ぢ
    2020-12-02 15:00

    You can add the following code for Collection in the Providers/AppServiceProvider.

        // Enable pagination
        if (!Collection::hasMacro('paginate')) {
    
            Collection::macro('paginate', 
                function ($perPage = 15, $page = null, $options = []) {
                $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
                return (new LengthAwarePaginator(
                    $this->forPage($page, $perPage)->values()->all(), $this->count(), $perPage, $page, $options))
                    ->withPath('');
            });
        }
    

    Then, you can call paginate from a Collection, just like an Eloquent model. For example

    $pages = collect([1, 2, 3, 4, 5, 6, 7, 8, 9])->paginate(5);
    

提交回复
热议问题