Convert Array to Collection with Pagination in Laravel
Today we’ll learn how to convert array to collection with pagination in Laravel. Let’s get started:
Table of Contents
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 TestControllerNow 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', 'TestController@test');That’s all. Now run the project and test.. Thank you.
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.
