Top View


Author Junkins

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

2019/01/10

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

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

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

バージョン
  • laravel 5.7
CakePHP3でいうと

CakePHP3の言葉でいうと、「Type」の機能になります。

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

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

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

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

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
 
 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',
];
 }

カスタマイズ方法

参考」を元に記載

  1. castAttribute()を拡張

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

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',
];
Junkins

Junkins

JenkinsじゃないよJunkinsです。紛らわしくてすいません。 元々PHPerでしたが、最近Rubyistになりました。