Reputation: 31
After I execute this query:
public function qryRecords($id)
{
$records = Record::with('place.country', 'place.city', 'place.organisation', 'framework', 'academy_year', 'status', 'type', 'student')
->where('student_id', '=', $id)
->get();
return response()->json($records);
}
I'd like to change the date format of academy_year, this is how it is kept in my database:
[
'start_date' => '2015-09-01',
'created_at' => now(),
'end_date' => '2016-06-30',
'is_archived' => true
],
Now in my model I do this to get the dates in datatables:
{
data: null,
render: function (data) {
return data.academy_year.start_date + ' <i class="fas fa-arrow-right"></i> <br> ' + data.academy_year.end_date;
}
},
I know of the method Carbon, but I'm not sure on how to use this in my situation. If it is possible with Carbon, I would love to hear, also if there are other methods I can use.
Upvotes: 0
Views: 4563
Reputation: 116
If you're fine with an additional library, you could try Moment.js.
For example:
{
data: null,
render: function (data) {
var formatted_start_date = moment(data.academy_year.start_date).format('dd.mm.yyyy')
var formatted_end_date = moment(data.academy_year.end_date).format('dd.mm.yyyy')
return formatted_start_date + ' <i class="fas fa-arrow-right"></i> <br> ' + formatted_end_date;
}
},
Please refer to the formatting docs if you want it to be formatted differently. https://momentjs.com/docs/#/displaying/format/
Upvotes: 0
Reputation: 1706
There are 2 ways of doing this, and the second option layers together with the first:
Record model:
protected $dates = [
'start_date',
'end_date'
];
Then, where you want to use the date into your custom format do this:
$record->start_date->format('d-m-Y');//Customize format as you want.
I would use this option, if the format does not need to change in the future, and only needs to be used a couple of times.
Record model:
function getFormattedStartDateAttribute()
{
return $this->start_date->format('d-m-Y');
}
When you want the formatted date, you can do:
$record->formatted_start_date;
I prefer the second option, because then you have to define the output format once, and then use $record->formatted_start_date every time you want the 'front-end-format'
Let me know if it works for you :)
Upvotes: 1