php Laravel 错误:在字符串上调用成员函数 format()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40533377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:11:13  来源:igfitidea点击:

Laravel error: Call to a member function format() on string

phplaravel

提问by zwl1619

I am using Laravel 5.3.

我正在使用 Laravel 5.3

There is a field expired_atin table articles

expired_at表中有一个字段articles

public function store(Request $request)
{
    $data=[
         'expired_at'=>Carbon::now()->addDays(30)->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)

在字符串上调用成员函数 format()(视图:D:\wnmp\www\laravel-5-3-dev\resources\views\artiles\index.blade.php)

Why is it?

为什么?

回答by Amit Gupta

In your Articleclass add following property:

在您的Article课程中添加以下属性:

/**
 * The attributes that should be mutated to dates.
 *
 * @var array
 */
protected $dates = ['expired_at'];

Docs

文档

回答by Nazmul Hasan

I think this is the way. It will not throw error

我认为这就是方法。它不会抛出错误

{{ Carbon\Carbon::parse($article->expired_at)->format('Y-m-d') }}

回答by Javier dc

If you use DB:: to retrieve complex data, you can′t use mutators. In this situation I use this:

如果你使用 DB:: 来检索复杂的数据,你就不能使用 mutator。在这种情况下,我使用这个:

{{ date('m-Y', strtotime($hora->Fecha)) }}

Or

或者

{{ date('m-Y', strtotime($hora ?? ''->Fecha)) }}

Where "Fecha" is a datetime value.

其中“Fecha”是日期时间值。