# Laravel オブジェクトのキャスト(Attribute Casting) + カスタマイズ方法

- URL: https://tech.fusic.co.jp/posts/laravel-attribute-casting-customize/
- 公開日: 2019-01-10
- 著者: Junkins
- 掲載: Fusic Tech Blog（株式会社Fusic）

> Laravel オブジェクトのキャスト (Attr…[続きを読むLaravel オブジェクトのキャスト(Attribute Casting) + カスタマイズ方法](https://tech.fusic.co.jp/uncategorized/laravel-attribute-casting-customize/)<!-- AddThis Advanced Settings generic via filter on get_the_excerpt --><!-- AddThis Share Buttons generic via filter on get_the_excerpt -->

---

# Laravel オブジェクトのキャスト

(Attribute Casting) + カスタマイズ方法

Laravelで行うオブジェクトのキャスト(Attribute Casting)の方法をまとめます。

##### バージョン

- laravel 5.7

##### CakePHP3でいうと

CakePHP3の言葉でいうと、「[Type](https://book.cakephp.org/3.0/ja/orm/database-basics.html#id8)」の機能になります。

##### 公式ドキュメントの記載場所

https://laravel.com/docs/5.7/eloquent-mutators#attribute-casting

### デフォルトで対応している型

下記のコードを読むとわかる

Illuminate\Database\Eloquent\Concerns\HasAttributes::castAttribute()

```php; title: 
switch ($this-\>getCastType($key)) { case 'int': case 'integer': return (int) $value; case 'real': case 'float': case 'double': return $this-\>fromFloat($value); case 'decimal': return $this-\>asDecimal($value, explode(':', $this-\>getCasts()[$key], 2)[1]); 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': return $this-\>asDate($value); case 'datetime': case 'custom\_datetime': return $this-\>asDateTime($value); case 'timestamp': return $this-\>asTimestamp($value); default: return $value; }
```

### 型の設定方法

公式ドキュメントの記載

```php; title: 
\<?php  namespace App;  use Illuminate\Database\Eloquent\Model;  class User extends Model { /\*\* \* The attributes that should be cast to native types. \* \* @var array \*/ protected $casts = [ 'is\_admin' =\> 'boolean',]; }
```

### カスタマイズ方法

「[参考](https://github.com/laravel/framework/pull/18229#issuecomment-428768007)」を元に記載

1. castAttribute()を拡張

例) 金額関係のAttribute Castingを行う方法

```php; title: 
protected function castAttribute($key, $value) { if (isset($this-\>casts[$key]) && $this-\>casts[$key] == 'money') { return number\_format($value); }  return parent::castAttribute($key, $value); }  protected $casts = [ 'price' =\> 'money',];
```
<!-- AddThis Advanced Settings generic via filter on the_content --><!-- AddThis Share Buttons generic via filter on the_content -->
