vendredi 1 juin 2018

Laravel 5.6 - Pass additional parameters to API Resource?

An API Resource can be either a single resource or a collection. In some cases, additional parameters are required to be passed to the resource/collection from the controller. Below is a simple example demonstrating the issue using User as a single/collection resource, and a custom $apple parameter to be passed to the resource for output. The issue can be seen in the final Output (Collection) below, where for the fruit value, we get an incorrect value of banana for the first user, instead of the correct apple value (which all other users get). It works perfectly for the single output, just not the collection. See below:

Controller with UserResource (Single)

$user = User::first();
return new UserResource($user, $apple = true); // $apple param passed

Controller with UserResource (Collection)

$users = User::limit(3)->get();
return UserResource::collection($users, $apple = true); // $apple param passed

UserResource

<?php

namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource {
    private $apple;

    public function __construct($resource, $apple = false) {
        // Ensure we call the parent constructor
        parent::__construct($resource);
        $this->resource = $resource;
        $this->apple = $apple; // $apple param passed
    }

    public function toArray($request) {
        return [
            'id'     => (int) $this->id, 
            'name'   => $this->name,
            'fruit'  => $this->apple ? 'apple' : 'banana',
        ];
    }
}

Output (Single)

{
    "data": {
        "id": 1,
        "name": "Peter",
        "fruit": "apple" // correct param!
    }
}

Output (Collection)

{
    "data": [
        {
            "id": 1,
            "name": "Peter",
            "fruit": "banana" // INCORRECT param!
        },
        {
            "id": 2,
            "name": "Lois",
            "fruit": "apple" // correct param!
        },
        {
            "id": 3,
            "name": "Brian",
            "fruit": "apple" // correct param!
        }
    ]
}

How can we fix this?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire