This Laravel package automatically casts your JsonResource data using the casting functions you have defined before.
This package makes easier to add global castings to your JsonResource files
You can install the package via composer:
composer require oguzhankrcb/auto-casting-json-resourceJust 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
];
}composer testPlease see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.