oguzhankrcb / auto-casting-json-resource
This Laravel package automatically casts your JsonResource data using the casting functions you have defined before.
v0.0.1
2022-09-14 12:35 UTC
Requires
- php: ^8.0
- laravel/framework: ^8.0 || ^9.0
- spatie/laravel-package-tools: ^1.9.2
Requires (Dev)
- brick/money: ^0.6.0
- nunomaduro/collision: ^6.0
- orchestra/testbench: ^7.7
- phpunit/phpunit: ^9.5
- spatie/laravel-ray: ^1.26
This package is auto-updated.
Last update: 2025-03-09 10:14:46 UTC
README
This package makes easier to add global castings to your JsonResource
files
Installation
You can install the package via composer:
composer require oguzhankrcb/auto-casting-json-resource
Usage
Just add this trait to your JsonResource
use AutoCastingJsonResource;
And then you can cast whatever you want in casts
array
/** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable */ public function toArray($request) { return $this->autoCast(parent::toArray($request)); } public function casts(): array { return [ 'integer' => fn ($value) => (int) ($value / 100), // It will divide all integer objects with 100 Money::class => fn (Money $value) => $value->getMinorAmount()->toInt() / 2, // It will cast all Brick\Money\Money objects to integer and divide them with 2 ]; }
You can exclude columns if you want (id
column is excluded by default)
public function excludedColumns(): array { return [ 'id', // id column will be excluded from castings ]; }
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.