dimanche 3 mars 2019

Different resource collection output for one model based on API version in Laravel

I want to have two different API version and want to have two different output of UserCollection. I've tried this:

class Branch extends JsonResource
{
    private $usage;

    public function __construct($resource, $usage = null) {
        $this->usage = $usage;
        parent::__construct($resource);
    }

    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id'    => (string) $this->id,
            'code'  => $this->code,
            'name'  => $this->name,
            $this->mergeWhen($this->usage == 'select-branch', [
                'address'   => $this->address,
                'phone'     => $this->phone,
            ]),
             $this->mergeWhen($this->usage == 'api', [
                'bank_id'   => $this->bank_id,
            ]),
        ];

        return $result;
    }
}

and no change in UserCollection.

But the first element has both merges and there is no merge for the rest.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire