Home > OS >  How to add prev and next links to Eloquent API resource collection?
How to add prev and next links to Eloquent API resource collection?

Time:08-25

How to add prev and next links to Laravel Eloquent API resource collection for one record, like pagination do this?

UPDATED:.
When we use pagination() the code should look like below:

public function index(): JsonResource
{
    $services = Service::paginate();

    return ServiceResource::collection($services);
}

and results like:

{
    "data": [
        {
            "id": 1,
            ...
        },
        {
            "id": 2,
            ...
        }
    ],
    "links":{
        "first": ...,
        "last": ...,
        "prev": "http://example.com/api/services?page=3",
        "next": "http://example.com/api/services?page=5"
    },
    ...
}

The question is, how to in the simple way add prev and next links in method (/api GET) for read one record, like below:

public function show(Service $service): JsonResource
{
    $service = Service::find($service);
}

to get response like this:

{
    "data": {
        "id": 346,
        ...
    },
    "links":{
        "prev": "http://example.com/api/services/345",
        "next": "http://example.com/api/services/347"
    },
    ...
}

CodePudding user response:

Model::all()->paginate(10);

so basically query and then do paginate with a number of records in braces. Then if u want to display links for listing pagination on front end u do

$variable->links()

Read more on Documentation

CodePudding user response:

You can have a custom api resource that does that :

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class IdResource extends JsonResource
{
    /**
     * Force withoutWrapping
     *
     * @param string $value
     */
    public static function wrap($value)
    {
        static::withoutWrapping();
    }

    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        $prev = $this->resource::where('id', '<', $this->resource->id)->first();
        $next = $this->resource::where('id', '>', $this->resource->id)->first();

        return [
            'data' => parent::toArray($request),
            'links' => [
                'prev' => $prev ? route('name', ['id' => $prev->id]) : null,
                'next' => $next ? route('name', ['id' => $next->id]) : null
            ]
        ];
    }
}

i don't think there is a way to make laravel do it by itself

  • Related