mohamed-ibrahem / advanced-json-resource
There is no license information available for the latest version (v0.9.0) of this package.
Advanced JSON laravel resources
v0.9.0
2023-03-08 11:45 UTC
Requires
- php: ^7.3|^8.0
- ext-json: *
- illuminate/support: ^8.0|^9.0|^10.0
Requires (Dev)
- orchestra/testbench: ^6.0|^7.0|^8.0
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^9.3
README
Create an advanced json responses for your Laravel application by creating a method for every response type, For example toIndex
, toShow
, toForm
, or a custom method name! Also you have shared
method for all shared attributes.
Installation
You can install the package via composer:
composer require mohamed-ibrahem/advanced-json-resource
Usage
Every resource should extends the AdvancedJsonResponse\ApiResource
class.
Now based on your response type you can create the methods.
And in the controller call these methods in snake case without to
in the beginning.
Example
use AdvancedJsonResource\ApiResource; use App\Models\User; use Illuminate\Http\Request; /** * @mixin User */ class UserResource extends ApiResource { /** * {@inheritdoc} * * @param Request $request * @return array<string, mixed> */ public function toIndex(Request $request): array { return [ 'name' => $this->name, ]; } /** * {@inheritdoc} * * @param Request $request * @return array<string, mixed> */ public function toShow(Request $request): array { return [ 'email' => $this->email, ]; } /** * {@inheritdoc} * * @param Request $request * @return array<string, mixed> */ public function toForm(Request $request): array { return [ 'can_update' => true, ]; } /** * This is a custom response method. * * @param Request $request * @return array<string, mixed> */ public function toCustom(Request $request): array { return [ 'custom' => 'custom', ]; } /** * {@inheritdoc} * * @param Request $request * @return array<string, mixed> */ public function shared(Request $request): array { return [ 'id' => $this->id, ]; } }
In the controller:
use App\Models\User; use App\Http\Resources\UserResource; use Illuminate\Http\Request; class UserController { public function index(): UserResource { return UserResource::index( User::all(), ); } public function store(Request $request): UserResource { //... return UserResource::form($user); } public function show(User $user): UserResource { return UserResource::show($user); } public function custom(Request $request, User $user): UserResource { return UserResource::cutsom($user); } }
Testing
composer test