Avinash kumawat
Avinash kumawat

Reputation: 75

Seperate date format for each field in laravel

I am using Laravel.In my model I defined dates and format. But I have "time_from" & "time_to" in format of "H:i:s" and "date" in "Y-m-d H:i:s" in my database. But I want to define separate date format for each three fields. Here is my code:

class MyModel extends Model
{
    protected $dates = ["time_from", "time_to", "date"];
    protected $dateFormat = "H:i:s";
}

So while fetching data from table , I can get Carbon object for each date field according to their format.

Upvotes: 3

Views: 306

Answers (1)

Daniel
Daniel

Reputation: 2777

Try use attribute casting in your model:

protected $casts = [
  'time_from' => 'datetime', // or timestamp
  'time_to' => 'datetime', // or timestamp
  'date' => 'date',
];

More: https://laravel.com/docs/5.4/eloquent-mutators#attribute-casting

Even, you can define an accessor for each field and return expected format.

Upvotes: 1

Related Questions