搜尋

首頁  >  問答  >  主體

Laravel 錯誤:呼叫字串上的成員函數 format()

資料表有個expired_at字段,資料是這樣的:


    public function store(Request $request)
    {
        $data=[
             'expired_at'=>Carbon::now()->addDays($publishing_days)->endOfDay()
        ];
        $article=Article::create(array_merge($request->all(),$data));
        
        return redirect('/artilces');
    }

view:

{{$article->expired_at->format('Y-m-d')}}

error:

Call to a member function format() on string (View: D:\wnmp\www\laravel-5-3-dev\resources\views\artiles\index.blade.php)

怎麼回事?

某草草某草草2822 天前1301

全部回覆(2)我來回復

  • PHPz

    PHPz2017-05-16 16:51:52

    這個錯誤訊息本身已經告訴你了啊, expire_at是字串, php中字串是沒有format方法的(其實沒有任何方法, 因為string在php中不是物件)

    回覆
    0
  • ringa_lee

    ringa_lee2017-05-16 16:51:52

    • 首先 expired_at 在資料庫中 需要為 timestamp 或者 datetime 類型

    • 其次, 在Model 中將 此欄位加入 $dates

    class Article extends Model {
        protected $dates = ['expired_at'];
    
    }

    接著就可以當Carbon呼叫了

    回覆
    0
  • 取消回覆