soyhuce/laravel-json-resources

An opinionated JsonResource for Laravel

1.6.0 2024-03-08 14:46 UTC

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status GitHub PHPStan Action Status Total Downloads

Don't ever run database queries in JsonResource serialization, without overhead in production !

Installation

You can install the package via composer:

composer require soyhuce/laravel-json-resources

You can publish the config file with:

php artisan vendor:publish --tag="json-resources-config"

Usage

This package provides a base class Soyhuce\JsonResources\JsonResource.

It gives a simplified interface for data serialization :

class UserResource extends \Soyhuce\JsonResources\JsonResource
{
    /**
     * @return array<string, mixed>
     */
    public function format(): array
    {
        return [
            'id' => $this->id,
            'email' => $this->email,
        ];
    }
}

It is still possible tu use public function toArray($request): array method.

A base class \Soyhuce\JsonResources\ResourceCollection est aussi disponible.

Forbid to execute database queries

Using this base resource, you can forbid to execute database queries during serialization.

You just need to activate this option in json-resources.forbid-database-queries config.

This configuration is thought to be used in local environments but should be deactivated in production. It allows you to tests that all required relations are correctly loaded (in feature tests for exemple) while limiting overhead in production.

For exemple :

class UserResource extends \Soyhuce\JsonResources\JsonResource
{
    /**
     * @return array<string, mixed>
     */
    public function format(): array
    {
        return [
            'id' => $this->id,
            'role' => $this->role->label,
        ];
    }
}

class UserController
{
    public function index(): \Illuminate\Http\Resources\Json\JsonResource
    {
        return UserResource::collection(User::all());
    }
}

A DatabaseQueryDetected exception will be raised with every executed request :

2 queries detected in resource :
select * from "roles" where "id" = 2
select * from "roles" where "id" = 1

AnonymousResource

It could be useful to have anonymous resources for some cases.

For exemple if user's role is nullable, you could have :

class UserResource extends \Soyhuce\JsonResources\JsonResource
{
    /**
     * @return array<string, mixed>
     */
    public function format(): array
    {
        return [
            'id' => $this->id,
            'role' => $this->role !== null 
                ? [
                    'id' => $this->role->id,
                    'label' => $this->role->label,
                ]
                : null
        ];
    }
}

Via an AnonymousResource, you could do

class UserResource extends \Soyhuce\JsonResources\JsonResource
{
    /**
     * @return array<string, mixed>
     */
    public function format(): array
    {
        return [
            'id' => $this->id,
            'role' => new \Soyhuce\JsonResources\AnonymousResource(
                $this->role,
                fn (Role $role) => [
                    'id' => $this->role->id,
                    'label' => $this->role->label,
                ]
            )
        ];
    }
}

If the user has a role, you will get :

{
  "data": {
    "id": 1,
    "role": {
      "id": 2,
      "label": "classic"
    }
  }
}

If the user doest not have a role, you will get :

{
  "data": {
    "id": 1,
    "role": null
  }
}

Returning anonymous resource from the controller

It is possible to return an anonymous resource from the controller. In cas the provided data is null, you won't get ' null' but an empty array [].

class SomeController
{
    public function show()
    {
        return \Soyhuce\JsonResources\AnonymousResource::make(
           $this->searchSomeItem(), // returns Item|null
           fn (Item $item) => [
               'label' => $item->label,
               'prop' => $item->prop 
           ]
        );
    }
}

If the item is found

{
  "data": {
    "label": "the label",
    "prop": 14
  }
}

If the item is null

{
  "data": []
}

Note : Anonymous resource collections are not supported

AnonymousResource without format

It is possible to return an anonymous resource without callback. In this case, the resource will be returned as is.

class SomeController
{
    public function show()
    {
        $foo = $this->fetchFoo();
        $bars = $this->fetchBars();
        
        return \Soyhuce\JsonResources\AnonymousResource::make([
           'foo' => FooResource::make($foo),
           'bars' => BarResource::collection($bars), 
       ]);
    }
}

Le json retourné aura alors la forme

{
  "data": {
    "foo": {
      // some foo data
    },
    "bar": [
      {
        // some bar data
      },
      {
        // some bar data
      }
    ]
  }
}

Json encoding

All returned jsons are encoded by default with JSON_PRESERVE_ZERO_FRACTION option.

Feature tests

The JsonResource and ResourceCollection classes will add a X-Json-Resource header to the response when the application is in local or testing environment.

This header will contain the actual resource class used to generate the response and can be used in functional tests to verify which resource was used.

In order to test this, you cas use TestResponse::assertJsonResource(TheResource::class) method.

use Soyhuce\JsonResources\Tests\Fixtures\User;

class SomeController
{
    public function index(): JsonResouce
    {
        return UserResource::collection(User::all());
    }
    
    public function show(User $user): JsonResource
    {
        return UserResource::make($user);
    }

}

class UserTest extends TestCase
{
    /** @test */
    public function indexUsesUserResource(): void
    {
        $this->getJson('users')
            ->assertOk()
            ->assertJsonResource(UserResource::class);
    }
    
    /** @test */
    public function showUsesUserResource(): void
    {
        $user = User:::factory()->createOne();
        
        $this->getJson("users/{$user->id}")
            ->assertOk()
            ->assertJsonResource(UserResource::class);
    }
}

Unit tests

It can be useful to unit test the JsonResource. You can use soyhuce/laravel-testing for this.

In this cas, you will probably need to allow database queries to be run. You can do this calling

\Soyhuce\JsonResources\JsonResources::allowDatabaseQueries();

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.