LoginSignup
41
29

More than 5 years have passed since last update.

【Laravel】DBから取得した値を$castsで型変換する【Attribute Casting】

Posted at

Laravelの$query->first()でDBの値を取得すると、DBのカラムの型がIntegerで定義していたとしても、返り値はすべてStringになります。

自分は今回、取得した値をさらに他の計算に使いたかったため、自動的にIntegerに変換してくれる処理を調べていました。
すると、LaravelのEloquentには、このために使用されるAttribute Casting(属性キャスト)という機能が備わっているそうです。

モデルの$castsプロパティにカラム名と変換したい型を指定すると、データアクセス時に型変換をしてくれます。

class Article extends Model
{
    protected $casts = [
        'pv' => 'integer'
    ];

// $article = Article::first();
// $article->pv がStringではなくIntegerに!

$castsで指定できる属性は、下記のLaravelのソースコードを見ると、[int, integer, real, float, double, string, bool, boolean, object, array, json, collection, date, datetime]に対応してるみたいです。

        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);
            default:
                return $value;

参考記事
https://laravel.com/docs/5.3/eloquent-mutators#attribute-casting
http://nextat.co.jp/staff/archives/140

41
29
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
41
29