vimuth
vimuth

Reputation: 5612

Date field must cast to 'date' in Eloquent model

Hi I'm using laravel nova for create an admin panel. And I'm trying to use Date Field.

This is my migration,

$table->date('day')->nullable();

This is my my nova resource,

public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),
            Date::make(__('Day'), 'day'),
        ];
    }

This is my model,

class Menu extends Model
{
    use HasTranslations;

    public $translatable = ['name','description'];

    protected $fillable = [
        'name','description','typology', 'cost', 'day', 'active', 'buffet'
    ];

This is my error,

Date field must cast to 'date' in Eloquent model.

Do I need to do anything in resource ?

Upvotes: 16

Views: 13102

Answers (1)

Julien METRAL
Julien METRAL

Reputation: 1974

In your model class you just need to add the following lines which describe to laravel that you must cast the day field into a date object (Carbon):

//Casts of the model dates
protected $casts = [
    'day' => 'date'
];

Check here someone has the same issue.

EDIT:

I have seen that your day column is set to nullable i think that your field Nova should be to like in this post :

public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),
            Date::make(__('Day'), 'day')->nullable(),
        ];
    }

And we need to change the model like this,

protected $casts = ['day' => 'date'];

Upvotes: 34

Related Questions