LoginSignup
4
3

More than 1 year has passed since last update.

Laravel date型カラムの取り扱いに注意

Last updated at Posted at 2021-09-09

エラーの詳細

例えばUserモデルにdate型のbirthdayというカラムがあるとする。

このbirthday

{{ $user->birthday->format('Y/m/d') }}
{{ $user->birthday->format('Y年m月d日') }}

上記のようにフォーマットを変更して表示する場合、Userモデルに

protected $dates = [
  'birthday'
];

とするとbirthdayCarbonインスタンスとなるため、フォーマットを変更できる。

しかし、フォーマットを変更して表示している場合birthdaynullだと下記のようなエラーになる。

Call to a member function format() on null
(nullなのにメンバー関数format()を呼び出しています)

エラーを回避するために下記のようなNull合体演算子を書いてみたが、それでもnullの場合、同じエラーになる。

{{ $user->birthday->format('Y/m/d') ?? '登録なし' }}

これはのbirthdayのフォーマットを変更した上でnull判定しようとしているのだが、フォーマットを変更するタイミングでbirthdaynullのため、やはり同じエラーが起こる。

解決策

birthdayのフォーマットを変更する前に条件分岐をすればいい。

// if文の場合
@if($user->birthday)
  {{ $user->birthday->format('Y/m/d') }}
@else
  登録なし
@endif

// 三項演算子の場合
{{ $user->birthday ? $user->birthday->format('Y/m/d') : '登録なし' }}

上記のようにすることで、birthdaynullでもエラーは起きなくなる。

ということでlaravelのdate型カラムの取り扱いには要注意です。

(自戒の念を込めて。)

4
3
1

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
4
3