0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Laravel】DBから取得したbooleanをtrue/falseに変換する$casts

Posted at

テーブルのカラムの型をboolean(true/false)で定義しているとします。
登録されているレコードの値を取得すると、以下のように0か1で返ってきます。
※DBはMySQL

$post = Post::first()
$post->is_draft // => 1 or 0

取得した値を基に条件分岐させたい場合、
一々、0をfalseに、1をtrueに変換させる処理が必要になります。
この処理を都度追加するのは正直だるいですね。
これを解決してくれるのが $casts になります。

使い方は対象のモデル内で$castsを以下のように定義して、型を指定してやるだけです。

protected $casts = [
    'is_draft' => 'boolean',
];

これだけで自動的にbooleanに変換してくれます。
冒頭で説明した同じコードを実行した場合、出力結果がちゃんとbooleanに変換されるようになりました。

$post = Post::first()
$post->is_draft // => true or false

上記はbooleanに変換していますが、
指定する型を変えれば、カラムの型によらず変換してくれるようになります。

参考

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?