Reputation: 4232
I am using Laravel 5.3
.
There is a field expired_at
in table 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)
Why is it?
Upvotes: 52
Views: 148824
Reputation: 17678
In your Article
class add following property:
From Laravel 10.x
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $casts = [
'expired_at' => 'datetime'
];
Before Laravel 10.x you could use
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['expired_at'];
Upvotes: 124
Reputation: 2407
Laravel 10 Update
The $dates
property has been deprecated and removed in Laravel 10. Instead, you should use the $casts
property. For example:
protected $casts = [
'expired_at' => 'datetime',
];
Upvotes: 3
Reputation: 66
You need to cast expired_at
into datetime in your Eloquent Model
. You get this error because you are calling format
function on a String, not a DateTime instance.
Upvotes: 0
Reputation: 809
What about this in User.php or your model:
protected $casts = [
'last_active_at' => 'datetime',
];
Upvotes: 5
Reputation: 11
With, the field declared on $dates of your model.
Try this:
optional($article->expired_at)->format('Y-m-d')
Upvotes: 1
Reputation: 575
If you use DB:: to retrieve complex data, you can´t use mutators. 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.
Upvotes: 14
Reputation: 1987
I think this is the way. It will not throw error
{{ Carbon\Carbon::parse($article->expired_at)->format('Y-m-d') }}
Upvotes: 70