Illuminate\Database\Eloquent\Model::castAttribute PHP Method

castAttribute() protected method

Cast an attribute to a native PHP type.
protected castAttribute ( string $key, mixed $value ) : mixed
$key string
$value mixed
return mixed
    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 (double) $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);
            default:
                return $value;
        }
    }

Usage Example

Example #1
0
 /**
  * Cast model attribute. Extend laravel attribute casting mutators by serialized array
  * @param string $key
  * @param mixed $value
  * @return mixed
  */
 protected function castAttribute($key, $value)
 {
     if ($value === null) {
         return $value;
     }
     if ($this->getCastType($key) === 'serialize') {
         return $this->fromSerialize($value);
     }
     return parent::castAttribute($key, $value);
 }
All Usage Examples Of Illuminate\Database\Eloquent\Model::castAttribute
Model