Support the ongoing development of Laravel.io →
posted 8 months ago
Laravel
Last updated by @asdf072 8 months ago.

sardorjs liked this thread

1
  • When you define a cast for contract_date as 'date:Y-m-d', Laravel internally uses this format when the model's date attributes are serialized to an array or JSON. This is useful for APIs or when you're passing data directly to JavaScript, for example.

  • When you access $job->contract_date in a Blade file, it returns a Carbon object. Carbon objects, when converted to strings, show the full date and time. Therefore, you see the time 00:00:00 appended to your date.

To avoid displaying the time in your Blade views, you have a couple of options:

  • Use toDateString() Method, as you mentioned
  • Format in Blade: <input value="{{ $job->contract_date->format('Y-m-d') }}">
  • Accessor in Model:
class Job extends Model
{
    protected $casts = [
        'contract_date' => 'date:Y-m-d',
    ];

    // Accessor
    public function getFormattedContractDateAttribute()
    {
        return $this->contract_date->format('Y-m-d');
    }
}

Then in Blade, you can use:

<input value="{{ $job->formatted_contract_date }}">

sardorjs liked this reply

1

Sign in to participate in this thread!

Eventy

Your banner here too?

SMills asdf072 Joined 3 Oct 2021

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.