简体   繁体   English

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

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

I am using Laravel 5.3 .我正在使用 Laravel 5.3

There is a field expired_at in table articlesarticles有一个字段expired_at

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?为什么?

In your Article class add following property:在您的Article类中添加以下属性:

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

Docs文档

I think this is the way.我认为这就是方法。 It will not throw error它不会抛出错误

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

If you use DB:: to retrieve complex data, you can´t use mutators.如果您使用 DB:: 来检索复杂数据,则不能使用修改器。 In this situation I use this:在这种情况下,我使用这个:

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

Or或者

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

Where "Fecha" is a datetime value.其中“Fecha”是日期时间值。

With, the field declared on $dates of your model.使用,在模型的 $dates 上声明的字段。

Try this:试试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM