DEV Community

Kingsconsult
Kingsconsult

Posted on

Pagination from Array in Laravel 8

Hello, Today I am going to be showing you how to create pagination in laravel from an array, sometimes we might find ourselves in a situation where we need to do some manipulation from the query result we got from the database or from an API before sending it to the view, if the array contains so many data, it might be cumbersome and messy to just populate it on a single page.
Laravel has a built-in function for pagination that is already integrated to Query builder and Eloquent ORM results of database which can be easily called like

$users = DB::table('users')->paginate(15);

But it cannot be applied to an array, so sit tight, we are going to be creating our own pagination from an array collection.

Click on my profile to follow me to get more updates.

For this article, I will be using code from my previous article on How to consume RESTful APIs in Laravel 8, what I want to do is grab the contents of an API (Github public API), extract some data, and store it in an array, then paginate the array and send it to the view (frontend).

Step 1: Setup your app

In case you don't have a laravel app running, you can click on this Link, and checkout step one on how to set up a laravel app.

Step 2: Add route

Go to routes/web.php and add the route to view our paginated array

Route::get('createpagination', [ProjectController::class, 'createPagination'])->name('createPagination');

Step 3: Create Controller Methods

Add the following methods to the app/Http/Controllers/ProjectController.php
Call the class at the top before the ProjectController Class

use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
Enter fullscreen mode Exit fullscreen mode

Then add this inside the class


    private function paginate($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);
    }

    public function createPagination() 
    {
        $client = new Client(); //GuzzleHttp\Client
        // Github public API to view my public Repositories
        $url = "https://api.github.com/users/kingsconsult/repos";


        $response = $client->request('GET', $url, [
            'verify'  => false,
        ]);
        $responseBody = json_decode($response->getBody());

        // Extract key, name, URL and date the repo was created
        // and store it in an array
        $responseArray = [];
        foreach ($responseBody as $key => $views) {
            $array = array('id' => $key, 'name' => $views->name, 'url' => $views->url, 'created_at' => $views->created_at);
            array_push($responseArray, $array);
        }

        // use the paginate method that we created to paginate the array and also 
        // add the URL for the other pages using setPath() method
        $githubRepo = $this->paginate($responseArray)->setPath('/projects/createpagination');

        return view('projects.createpagination', compact('githubRepo'))
        ->with('i', (request()->input('page', 1) - 1) * 5)
        ;
    }
Enter fullscreen mode Exit fullscreen mode

Step 4: Create View

Go to resources/views/projects and create a blade file called createpagination.blade.php and add the following code

@extends('layouts.app')

@section('content')

<style>

</style>
<div class="row mb-3">
    <div class="col-lg-12 margin-tb">
        <div class="text-center">
            <h2>Github Public Repository</h2>
            <a class="btn btn-primary" href="{{ route('projects.index') }}" title="Go back"> <i class="fas fa-backward fa-2x"></i> </a>
        </div>
    </div>
</div>

<div class="container-fluid mb-5" style="margin-bottom: 150px !important">
    <div class="row mr-4">

 <table class="table table-bordered table-responsive-lg">
    <tr>
        <th>No</th>
        <th>Name</th>
        <th>Url</th>
        <th>Date Created</th> 
    </tr>
    @foreach ($githubRepo as $repo)
    <tr>
        <td>{{ ++$i }}</td>
        <td>{{ $repo['name'] }}</td>
        <td>{{ $repo['url'] }}</td>
        <td>{{ $repo['created_at'] }}</td>
    </tr>
    @endforeach
</table>
{!! $githubRepo->links() !!}
    </div>
</div>


@endsection
Enter fullscreen mode Exit fullscreen mode

Step 5: Use Bootstrap for the pagination links

If we don't indicate that we are going to use Boostrap for the pagination, the pagination links will be displaying weird arrows, so to style our pagination links, go to app/Providers/AppServiceProvider.php and tell the app to use Bootstrap in pagination, add this to the boot method

Paginator::useBootstrap();

and at the top, add this also

use Illuminate\Pagination\Paginator;

Result
http://127.0.0.1:8000/projects/createpagination?page=3

Follow me for more of my articles, you can leave comments, suggestions, and reactions

Top comments (0)