Laravel – Convert Array to Collection with Pagination

0
1238
array to collection laravel

In this article, we will learn how we can convert an array to collection with pagination. To achieve this, we will build a simple function to convert an array to a collection.

Let’s first add a route for displaying our records with pagination. Simply, add the below code in your web.php routes file.

//web.php
Route::get('array-to-collection', 'DemoController@index');

Now, we will create a new controller DemoController with index method inside it so that when we hit the route array-to-collection, this method will be hit. Let’s write some code into our controller and describe the process later.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
  
class DemoController extends Controller
{
    /**
     * Convert array to collection method
     *
     * @var view
     */
    public function index()
    {
        $array = [
            ['id'=>1, 'title'=>'Demo Article 1'],
            ['id'=>2, 'title'=>'Demo Article 2'],
            ['id'=>3, 'title'=>'Demo Article 3'],
            ['id'=>4, 'title'=>'Demo Article 4'],
            ['id'=>5, 'title'=>'Demo Article 5'],
            ['id'=>6, 'title'=>'Demo Article 6'],
            ['id'=>7, 'title'=>'Demo Article 7'],
            ['id'=>8, 'title'=>'Demo Article 8'],
            ['id'=>9, 'title'=>'Demo Article 9'],
            ['id'=>10, 'title'=>'Demo Article 10'],
        ];
  
        $articles = $this->convertArrayToCollection($array);
   
        dd($articles);
    }
   
    /**
     * helper function to convert array to paginated collection
     *
     * @var collection
     */
    public function convertArrayToCollection($items, $perPage = 5, $page = null, $options = [])
    {
        $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
        $items = $items instanceof Collection ? $items : Collection::make($items);
        return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
    }
}

In the above code, we are creating a simple array $array. Then, we are creating a convertArrayToCollection method which converts our array to the paginated collection. If we visit the route /array-to-collection route, we will see the collection with pagination instead of an array.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.