achrafbardan/simple-resources

This is my package simple-resources-for-laravel

1.0.1 2023-05-19 08:26 UTC

This package is auto-updated.

Last update: 2024-04-19 10:31:13 UTC


README

Latest Version on Packagist GitHub Tests Action Status Total Downloads

This is a small package that simplifies resource usage. It is used to auto guess and link resources to models. Paginated collections are also auto wrappable in the resource.

Installation

You can install the package via composer:

composer require AchrafBardan/simple-resources-for-laravel

You can publish the config file with:

php artisan vendor:publish --tag="simple-resources-for-laravel-config"

This is the contents of the published config file:

return [
    "model_namespace" => "App\\Models",
    "resource_namespace" => "App\\Http\\Resources",

    /**
     * When this is set to false, you have to add the \AchrafBardan\SimpleResources\Contracts\HasResource interface to your models.
     * When set to true you can still optionally add the interface to your models, this interface will than be used instead of the guesser.
     */
    "guess_resource" => true
];

Optionally, you can publish the views using

php artisan vendor:publish --tag="simple-resources-for-laravel-views"

Usage

Before returning a model or collection you pass it trough the ResourceFactory. The resource factory finds the resource for your model, collection or even a paginated collection.

use AchrafBardan\SimpleResources\ResourceFactory;
...
$resource = ResourceFactory::make($model);
return response()->json($resource);

You can also use the helper function resource which is the same as ResourceFactory::make

use function AchrafBardan\SimpleResources\resource;
...
$resource = resource($model);
return response()->json($resource);

It also intended to be used inside a resource for child models and collections, see the following example.

// App/Http/Resources/TestResource.php
...
class TestResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'child' => resource($this->whenLoaded('child'))
        ];
    }
}

Testing

composer test

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.