![Software License][ico-license] [![Total Downloads][ico-downloads]][link-downloads]
This packages allows you to add extra parameters to your Eloquent API resources and collections.
Highly inspired by gdebrauwer's issue answer and his pull-request.
Require the manajet/laravel-extra-resource
package in your composer.json
and update your dependencies:
composer require manajet/laravel-extra-resource
You can create a new resource with this command:
php artisan make:extraresource MyResource
As well as Laravel make:resource command, you can pass --collection
option to create a new collection with extra parameters:
php artisan make:extraresource MyCollection --collection
You can use your resources as you did before. To pass extra parameters, use the using
method.
Resource:
$user = User::find(1);
return (new UserResource($user))->using(['foo' => 'bar']);
And in your Resource class:
<?php
namespace App\Http\Resources;
use Manajet\ExtraResource\ExtraJsonResource;
class UserResource extends ExtraJsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'foo' => $this->extra['foo'],
];
}
}
Collection:
Collection will try to use your Resource class, so you need to create it first.
$users = User::all();
return (new UserCollection($users))->using(['foo' => 'bar']);
You can also use it with the static collection
method:
$users = User::all();
return UserResource::collection($users)->using(['foo' => 'bar']);
Released under the MIT License, see LICENSE.