zwl1619
zwl1619

Reputation: 4232

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

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

Answers (7)

Amit Gupta
Amit Gupta

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'
];

Laravel 10 Upgrade

Before Laravel 10.x you could use

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

Docs

Upvotes: 124

JasonJensenDev
JasonJensenDev

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

DragonHeart26
DragonHeart26

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

James Wilson
James Wilson

Reputation: 809

What about this in User.php or your model:

protected $casts = [
   'last_active_at' => 'datetime',
];

Upvotes: 5

Guilherme Cagnini
Guilherme Cagnini

Reputation: 11

With, the field declared on $dates of your model.

Try this:

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

Upvotes: 1

Javier dc
Javier dc

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

Nazmul Hasan
Nazmul Hasan

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

Related Questions