faustbrian/eloquent-castable

More extensible Attribute Casting for Eloquent

2.1.0 2017-01-20 12:20 UTC

README

Build Status PHP from Packagist Latest Version License

Installation

Require this package, with Composer, in the root directory of your project.

$ composer require faustbrian/eloquent-castable

Usage

<?php

class Product extends Eloquent
{
    use \BrianFaust\Castable\Castable;

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'price' => 'money'
    ];

    /**
     * The user defined caster classes.
     *
     * @var array
     */
    protected $customCasters = [
        'money' => \App\Casters\MoneyCaster::class
    ];

    /**
     * Config for \App\Casters\MoneyCaster
     *
     * @return array
     */
    public function getMoneyCasterConfig()
    {
        return ['currency' => $this->invoice->currency->code];
    }
}
<?php

namespace App\Casters;

use BrianFaust\Castable\Casters\AbstractCaster;

class MoneyCaster extends AbstractCaster
{
    /**
     * {@inheritdoc}
     */
    public function save($value)
    {
        return $value;
    }

    /**
     * {@inheritdoc}
     */
    public function load($value)
    {
        return new Money((int) $value, new Currency($this->options['currency']));
    }
}

Testing

$ phpunit

Security

If you discover a security vulnerability within this package, please send an e-mail to hello@brianfaust.me. All security vulnerabilities will be promptly addressed.

Credits

License

MIT © Brian Faust