5
2

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 getFormattedDueDateAttributeでTrailing data のエラーが出た場合

Posted at

初めに

仕事でLaravelの知識が必要となり、下記リンクの良さげなチュートリアルをやっていまた。
https://www.hypertextcandy.com/laravel-tutorial-todo-app-list-tasks

チュートリアル通りにやっていてもエラーってやっぱり起きるのですよね〜。。。

環境

チュートリアルが2018年のものだったので、少し古めのv6でやってみた(この時、もっと詳しく年代別のバージョンを調べていれば・・・:persevere:

$ php artisan --version
Laravel Framework 6.18.40

問題の箇所

上記リンク先のチュートリアルである**「日付の表示形式を変更する」**の部分

Task.php
// この行を追加
use Carbon\Carbon;

class Task extends Model
{
    /* 中略 */

    /**
     * 整形した期限日
     * @return string
     */
    public function getFormattedDueDateAttribute()
    {
        return Carbon::createFromFormat('Y-m-d', $this->attributes['due_date'])
            ->format('Y/m/d');
    }
}

Carbon ライブラリを使って期限日の値の形式を変更して返す部分で、以下のようなエラーが!

Carbon\Exceptions\InvalidFormatException
Trailing data (View: /Users/***/resources/views/tasks/index.blade.php)

全てコピペし直したりしたので、どう考えてもスペルミスではない。とすると、、、

バージョンによる違いでした。。

上記stackoverflowで見た回答を試すとエラーは解消された。。。
おそらくv5とv6の違いなのでしょう。

Task.php
  /**
     * 整形した期限日
     * @return string
     */
   public function getFormattedDueDateAttribute()
    {
        // createFromFormatの中を 'Y-m-d H:i:s'に変更する
        return Carbon::createFromFormat('Y-m-d H:i:s', $this->attributes['due_date'])
        ->format('Y/m/d');
    }

と言うか、チュートリアルのページをよく見ると、以下のようなコメントもありました:joy:

お世話になります。
Laravel6.14.0です。
後半の「日付の表示形式を変更する」の項で、getFormattedDueDateAttributeを追加し、テンプレートの修正をしてブラウザを再読み込みしたところ、「trailing error」が出ました。
createFromFormat内を('Y-m-d H:i:s' , ......)と修正したところ、解決しました。
念のため、お知らせしておきます。

5
2
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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?