achrafbardan / simple-resources
This is my package simple-resources-for-laravel
Requires
- php: ^8.0|^8.1|^8.2|^8.3
- illuminate/contracts: ^9.0|^10.0|^11.0
- spatie/laravel-package-tools: ^1.16.4
Requires (Dev)
- laravel/pint: ^1.0
- nunomaduro/collision: ^6.0
- nunomaduro/larastan: ^2.0.1
- orchestra/testbench: ^7.0
README
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.