Convert Array to Collection with Pagination in Laravel

Published on June 7, 2020 1 min read

Today we’ll learn how to convert array to collection with pagination in Laravel. Let’s get started:

Table of Contents

  1. Create Support File
  2. Make Test Controller
  3. Define Route and Test

Create Support File

Navigate to app directory and create folder named Support. Under Support folder, create a file called Collection.php and then paste this code:

app/Support/Collection.php
<?php

namespace App\Support;

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

class Collection extends BaseCollection
{
    public function paginate($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,
            ]
        );
    }
}

This support file will convert array to collection with pagination.

Make Test Controller

Let’s create a test controller:

php artisan make:controller TestController

Now open the controller and paste this code:

app/Http/Controllers/TestController.php
<?php

namespace App\Http\Controllers;

use App\Support\Collection;
use Illuminate\Http\Request;

class TestController extends Controller
{
    public function test() {
        // the array
        $the_array = [
            ['id'=>1, 'title'=>'Post 1'],
            ['id'=>2, 'title'=>'Post 2'],
            ['id'=>3, 'title'=>'Post 3'],
            ['id'=>4, 'title'=>'Post 4'],
            ['id'=>5, 'title'=>'Post 5'],
            ['id'=>6, 'title'=>'Post 6'],
            ['id'=>7, 'title'=>'Post 7'],
            ['id'=>8, 'title'=>'Post 8'],
            ['id'=>9, 'title'=>'Post 9'],
            ['id'=>10, 'title'=>'Post 10'],
        ];

        // convert array to collection with pagination
        $per_page = 2;
        $results = (new Collection($the_array))->paginate($per_page);

        dd($results);
    }
}

in the controller, I’ve written an array to test.

Define Route and Test

Define a route for the test function:

routes/web.php
Route::get('/test', '[email protected]');
That’s all. Now run the project and test.. Thank you. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development. If you enjoy my content, please consider supporting what I do!

Follow Buy me a coffeeBuy me a coffee

Leave a Reply

Your email address will not be published. Required fields are marked *