appson
appson

Reputation: 183

paginate method for data obtained from external api

I'm wondering if it is possible to automate the pagination process for data obtained from external API like

$users = App\User::paginate(15);

for models. Maybe do you know any packages? I want to make something like that

        $client = new \GuzzleHttp\Client();
        $res = $client->request('GET', 'https://xxx');
        $data = $res->getBody();
        $res = json_decode($data );
       ///pagination

Do you know any solutions? Is the only one way to create pagination manually?

Upvotes: 3

Views: 2214

Answers (1)

hoseinz3
hoseinz3

Reputation: 638

You could use Laravel resource.

First: create a single resource (I suppose your API is about Post)

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Post extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
          'name' => $this->resource['name'],
          'title' => $this->resource['title']

        ];
    }
}

Second: create a resource collection

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class PostCollection extends ResourceCollection
{
    public function toArray($request)
    {
        return [
            'data' => $this->collection
                ->map
                ->toArray($request)
                ->all(),
            'links' => [
                'self' => 'link-value',
            ],
        ];
    }
}

after that you could set your api data to collection like this:

$client = new \GuzzleHttp\Client();
$res = $client->request('GET', 'https://xxx');
$data = $res->getBody();
$res = collect(json_decode($data));
return PostCollection::make($res);

and for add pagination to your resource collection you could do this:

$res = collect(json_decode($data));

$page = request()->get('page');
$perPage = 10;
$paginator = new LengthAwarePaginator(
    $res->forPage($page, $perPage), $res->count(), $perPage, $page
);

return PostCollection::make($paginator);

for reading more about Laravel collection visit laravel documentation.

for knowing more about Consuming third-party APIs with Laravel Resources visit this great article.

Upvotes: 5

Related Questions