lundi 27 février 2017

Laravel 5.3 how to write custom casted attribute

I have Trait for custom cast types and added currency cast type but it works only when accessing attribute:

trait ModelCastsTrait {

protected function castAttribute($key, $value)
{
    if (is_null($value)) {
        return $value;
    }

    switch ($this->getCastType($key)) {
        case 'int':
        case 'integer':
            return (int) $value;
        case 'real':
        case 'float':
        case 'double':
            return (float) $value;
        case 'string':
            return (string) $value;
        case 'bool':
        case 'boolean':
            return (bool) $value;
        case 'object':
            return $this->fromJson($value, true);
        case 'array':
        case 'json':
            return $this->fromJson($value);
        case 'collection':
            return new BaseCollection($this->fromJson($value));
        case 'date':
        case 'datetime':
            return $this->asDateTime($value);
        case 'timestamp':
            return $this->asTimeStamp($value);
        case 'currency':
            return new CurrencyCast($value, $this);
        default:
            return $value;
    }
}

}

How make custom attribute casting work in reverse, convert value to castable type?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2mv6Wpw
via IFTTT

Aucun commentaire:

Enregistrer un commentaire