vlauciani
vlauciani

Reputation: 1100

Laravel 8 - Date Casting

I'm confused using Date Casting (https://laravel.com/docs/8.x/eloquent-mutators#date-casting) in Laravel 8.

I need to get, from DB, all my date fields with format Y-m-d\TH:i:s.vP; for example: 1990-02-12T01:08:12.820+00:00.

To do that, in my Origin Model, I set:

class Origin extends Model
{
    protected $casts = [
        'myDate' => 'datetime:Y-m-d\TH:i:s.vP'
    ];
}

Now, the field myDate is casted to Carbon:

$ php artisan tinker
>>>
>>> $origin = App\Origin::first();
>>>
>>> dd($origin->myDate);
Illuminate\Support\Carbon @634784892^ {#4629
  #constructedObjectId: "000000005620d556000000007f71416e"
  #localMonthsOverflow: null
  #localYearsOverflow: null
  #localStrictModeEnabled: null
  #localHumanDiffOptions: null
  #localToStringFormat: null
  #localSerializer: null
  #localMacros: null
  #localGenericMacros: null
  #localFormatFunction: null
  #localTranslator: null
  #dumpProperties: array:3 [
    0 => "date"
    1 => "timezone_type"
    2 => "timezone"
  ]
  #dumpLocale: null
  date: 1990-02-12 01:08:12.820 UTC (+00:00)
}
>>>
>>>

but when I get the attribute, the output doesn't respect the format Y-m-d\TH:i:s.vP:

>>>
>>> echo $origin->myDate;
1990-02-12 01:08:12⏎
>>>
>>>

to obtain the required format, I need to format It again:

>>>
>>> echo $origin->myDate->format('Y-m-d\TH:i:s.vP');
1990-02-12T01:08:12.820+00:00⏎
>>>
>>>

or convert the Model toArray() before using it:

>>>
>>> echo $origin->toArray()['myDate'];
1990-02-12T01:08:12.820+00:00⏎
>>>
>>>

What is the best practice the set the date format and get the correct output? I'd like to use:

>>>
>>> echo $origin->myDate;
1990-02-12T01:08:12.820+00:00⏎
>>>
>>>

Thank you

Upvotes: 0

Views: 3217

Answers (2)

chapskev
chapskev

Reputation: 982

This is a late answer but might help someone or myself.

Cast will not format the date as it expect a primitive data type with no formatting options, the same for float data type where by we cannot specify the decimal places.

To format date use Carbon format options on the model

class Origin extends Model
{
    protected $dates = [
        'myDate' => 'datetime:Y-m-d\TH:i:s.vP'
    ];

}

Upvotes: 0

Kamlesh Paul
Kamlesh Paul

Reputation: 12391

as your saying laravel casting format is not working you can create accessor like this

class Origin extends Model
{
    protected $casts = [
        'myDate' => 'datetime:Y-m-d\TH:i:s.vP'
    ];


    public function getMyDateAttribute($value)
    {
        return $value->format('Y-m-d\TH:i:s.vP');
    }
}

it will make sure you will always return this format

ref link https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor

Upvotes: 1

Related Questions