Skip to content

This Laravel package automatically casts your JsonResource data using the casting functions you have defined before.

License

Notifications You must be signed in to change notification settings

oguzhankrcb/auto-casting-json-resource

Repository files navigation

This Laravel package automatically casts your JsonResource data using the casting functions you have defined before.

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status

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.

About

This Laravel package automatically casts your JsonResource data using the casting functions you have defined before.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages