Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

anjanesh's avatar

Why set casts in model when its date in migration ?

In my migration :

        Schema::create('news', function (Blueprint $table) {
            $table->id();
            // ...
            $table->date('published');
            $table->timestamps();
        });

In app/Nova/News.php

    public function fields(NovaRequest $request)
    {
        return [
            ID::make()->sortable(),

            / ...

            Date::make('Published Date', 'published')
            ->sortable()
            ->rules('required'),
        ];
    }

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

I had to do in app/Models/News.php to make it work.

    protected $casts = [
        'published' => 'date' # datetime:Y-m-d
    ];

Why do I have to do this extra casts when in my migration its clearly date type and and in Nova I'm setting it to Date::make ?

0 likes
1 reply
Niush's avatar
Niush
Best Answer
Level 50

Database will return date field as simple string. And, Laravel does not check the database table Schema every single time to know what the column type is. Only after the data is fetched, it will cast using the casts array provided. Try using DB::table('news')->get() to see the raw result.

Please or to participate in this conversation.