Separate date format for each field in laravel
I am using Laravel. In my model, I have defined dates and format. But I have "time_from" and "time_to" in "H: i: s" format and "date" in "Ymd H: i: s" in my database. But I want to define a separate date format for every three fields. Here is my code:
class MyModel extends Model
{
protected $dates = ["time_from", "time_to", "date"];
protected $dateFormat = "H:i:s";
}
So by getting data from a table, I can get a Carbon object for each date field according to their format.
+3
source to share
1 answer
Try using the casting attribute on your model:
protected $casts = [
'time_from' => 'datetime', // or timestamp
'time_to' => 'datetime', // or timestamp
'date' => 'date',
];
More details: https://laravel.com/docs/5.4/eloquent-mutators#attribute-casting
Even you can define an accessory for each field and return the expected format.
+1
source to share