0
1

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 3 years have passed since last update.

【Laravel】Time型のレコードをフォーマットして出力する時のエラーの回避対策

Last updated at Posted at 2021-06-17

Time型のレコードを出力したい時に、少し手間取ったのでメモを残します。

使用環境

Laravel 6.2
MySQL 8.0

現象

Time型のレコードをbladeにformat(時:分)して出力をしたいが、エラーがでます。

xxx.blade.php
{{ $model->start_time->format('hh:ii') }}

Call to a member function format() on string

エラーを調べると、modelにカラムを追加すると解消できるとありました。
公式では、「日付ミューテタ」とあります。

model.php
protected $dates = [
        'start_time', 
    ];

ですが、また別のエラーが出力されました。

Unexpected data found. Unexpected data found. Data missing

所謂、取り出すデータと出力するフォーマットが異なっているエラーだと思います。

結論

そもそも、Time型の値を日付ミューテタにするのは間違いです。
日付ミューテタと言っているくらいなので、Date型などの日付に絡んだレコード出ないといけません。

また、Call to a member function format() on string
文字列をformatできないエラーです。
DBから直接、値を出力しているため文字列になります。

では、一番簡単に(時:分)で出力するためには??

対策

substrを使うと手っ取り早いです!
以下、PHP公式マニュアルです。

substr(string $string, int $offset, int|null $length = null): string
文字列 string の、offset で指定された位置から length バイト分の文字列を返します。

なので、(時:分)で表すには、

xxx.blade.php
{{ substr($model->start_time,0,5) }}

これで出力できます。

参考

https://teratail.com/questions/192540
https://qiita.com/shimotaroo/items/acd22877a09fb13827fb
https://readouble.com/laravel/6.x/ja/eloquent-mutators.html
https://www.php.net/manual/ja/function.substr.php

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?