Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 788
vimuth Avatar asked Mar 12 '19 09:03

vimuth


Video Answer


1 Answers

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'];
like image 56
Julien METRAL Avatar answered Oct 13 '22 02:10

Julien METRAL