PHPackages                             soyhuce/laravel-json-resources - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. soyhuce/laravel-json-resources

ActiveLibrary[API Development](/categories/api)

soyhuce/laravel-json-resources
==============================

An opinionated JsonResource for Laravel

1.9.0(2mo ago)213.5k[2 PRs](https://github.com/Soyhuce/laravel-json-resources/pulls)MITPHPPHP ^8.3CI passing

Since Mar 9Pushed 3mo ago2 watchersCompare

[ Source](https://github.com/Soyhuce/laravel-json-resources)[ Packagist](https://packagist.org/packages/soyhuce/laravel-json-resources)[ Docs](https://github.com/soyhuce/laravel-json-resources)[ GitHub Sponsors](https://github.com/soyhuce)[ RSS](/packages/soyhuce-laravel-json-resources/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (23)Versions (15)Used By (0)

An opinionated JsonResource for Laravel
=======================================

[](#an-opinionated-jsonresource-for-laravel)

[![Latest Version on Packagist](https://camo.githubusercontent.com/b4949f344a33ff4e9d74513aea2634c56e150cb2546d5f7c121b9999ac56c7ec/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f736f79687563652f6c61726176656c2d6a736f6e2d7265736f75726365732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/soyhuce/laravel-json-resources)[![GitHub Tests Action Status](https://camo.githubusercontent.com/09f0111baec81a11bc3254301903dca99acdb3c4f3929c9708d7f80faf2626c9/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f736f79687563652f6c61726176656c2d6a736f6e2d7265736f75726365732f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/soyhuce/laravel-json-resources/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/3bea665bc761ba2f26bd9c501112b5af2c682ea6b389ab136135a0c9a6977e19/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f736f79687563652f6c61726176656c2d6a736f6e2d7265736f75726365732f7068702d63732d66697865722e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/soyhuce/laravel-json-resources/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![GitHub PHPStan Action Status](https://camo.githubusercontent.com/19a1688409ecf6ee8fce785cce354057aeba1c64acc6b54665bed2204aa5de11/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f736f79687563652f6c61726176656c2d6a736f6e2d7265736f75726365732f7068707374616e2e796d6c3f6272616e63683d6d61696e266c6162656c3d7068707374616e)](https://github.com/soyhuce/laravel-json-resources/actions?query=workflow%3APHPStan+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/b341db99545f2887197433eb1bd6c8db273bf3548c0d973deb24437cf265d168/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f736f79687563652f6c61726176656c2d6a736f6e2d7265736f75726365732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/soyhuce/laravel-json-resources)

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

Installation
------------

[](#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
-----

[](#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
     */
    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

[](#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
     */
    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

[](#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
     */
    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
     */
    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

[](#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

[](#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

[](#json-encoding)

All returned jsons are encoded by default with `JSON_PRESERVE_ZERO_FRACTION` option.

### Feature tests

[](#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

[](#unit-tests)

It can be useful to unit test the `JsonResource`. You can use [soyhuce/laravel-testing](https://github.com/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
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Bastien Philippe](https://github.com/bastien-phi)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

52

—

FairBetter than 96% of packages

Maintenance82

Actively maintained with recent releases

Popularity27

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~145 days

Recently: every ~211 days

Total

11

Last Release

71d ago

PHP version history (3 changes)1.0.0PHP ^8.1

1.5.0PHP ^8.2

1.7.0PHP ^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/206cfbf866a463f7e7d1e86946d59b82f4191b9c89f9981fb03eeb264d77af79?d=identicon)[SoyHuCe](/maintainers/SoyHuCe)

---

Top Contributors

[![bastien-phi](https://avatars.githubusercontent.com/u/10199039?v=4)](https://github.com/bastien-phi "bastien-phi (36 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (20 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (12 commits)")[![EdenMl](https://avatars.githubusercontent.com/u/70885551?v=4)](https://github.com/EdenMl "EdenMl (5 commits)")[![ElRochito](https://avatars.githubusercontent.com/u/1737307?v=4)](https://github.com/ElRochito "ElRochito (4 commits)")

---

Tags

hacktoberfestlaravellaraveljson-resourcessoyhuce

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/soyhuce-laravel-json-resources/health.svg)

```
[![Health](https://phpackages.com/badges/soyhuce-laravel-json-resources/health.svg)](https://phpackages.com/packages/soyhuce-laravel-json-resources)
```

###  Alternatives

[ryangjchandler/bearer

Minimalistic token-based authentication for Laravel API endpoints.

8129.8k](/packages/ryangjchandler-bearer)[stechstudio/laravel-hubspot

A Laravel SDK for the HubSpot CRM Api

2971.0k](/packages/stechstudio-laravel-hubspot)[simplestats-io/laravel-client

Client for SimpleStats!

4515.5k](/packages/simplestats-io-laravel-client)[scalar/laravel

Render your OpenAPI-based API reference

6183.9k2](/packages/scalar-laravel)[combindma/laravel-facebook-pixel

Meta pixel integration for Laravel

4956.9k](/packages/combindma-laravel-facebook-pixel)[njoguamos/laravel-plausible

A laravel package for interacting with plausible analytics api.

208.8k](/packages/njoguamos-laravel-plausible)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
