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:


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(),
                '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:


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);


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

Define Route and Test

Define a route for the test function:

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

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.

Hey, I'm Md Obydullah. I build open-source projects and write article on Laravel, Linux server, modern JavaScript and more on web development.


One Reply to “Convert Array to Collection with Pagination in Laravel”

Leave a Reply