Skip to content

manajet/laravel-extra-resource

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Extra Resource for Laravel

![Software License][ico-license] [![Total Downloads][ico-downloads]][link-downloads]

About

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.

Installation

Require the manajet/laravel-extra-resource package in your composer.json and update your dependencies:

composer require manajet/laravel-extra-resource

Create 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

Usage

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']);

License

Released under the MIT License, see LICENSE.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages