How to paginate a Magic the Gathering API with Laravel?

Updated: Feb 12, 2025

How to paginate a Magic the Gathering API with Laravel?

To paginate data from the Magic the Gathering API using Laravel, you'll need to make a few adjustments to your code. Here's a step-by-step guide on how to do it:

  1. Install the Laravel Pagination package:

First, you need to install the Laravel Pagination package if you haven't already. You can install it via composer by running the following command in your terminal:

composer require laravel/pagination
  1. Fetch data from the Magic the Gathering API:

Assuming you have a method in your controller to fetch data from the Magic the Gathering API, you can call it fetchData():

public function fetchData()
{
    $response = file_get_contents('https://api.scryfall.com/cards/random?grant_id=YOUR_GRANT_ID');
    $data = json_decode($response, true);

    return $data;
}

Replace YOUR_GRANT_ID with your actual grant ID.

  1. Paginate the fetched data:

Create a new method in your controller to paginate the data:

public function paginateData($page = 1)
{
    $data = $this->fetchData();

    $paginatedData = array_slice($data, ($page - 1) * 10, 10);

    return view('your-view')->with('data', $paginatedData);
}

Replace your-view with the name of your view file. In this example, we assume that you want to display 10 cards per page. Adjust the number of cards per page as needed.

  1. Update your route:

Update your route file to call the paginateData() method:

Route::get('/cards', 'YourController@paginateData');

Replace YourController with the name of your controller.

  1. Display the data in your view:

Finally, update your view file to display the paginated data:

@extends('layouts.app')

@section('content')
<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Type</th>
            <th>Set</th>
        </tr>
    </thead>
    <tbody>
        @foreach ($data as $card)
            <tr>
                <td>{{ $card['name'] }}</td>
                <td>{{ $card['type'] }}</td>
                <td>{{ $card['set'] }}</td>
            </tr>
        @endforeach
    </tbody>
</table>

{!! $data->links() !!}
@endsection

Replace the table headers and columns with the actual fields you want to display.

Now, when you visit the /cards route, you should see the first 10 cards displayed, and you can navigate to the next page by clicking the "Next" button.