I am using Laravel and Vue js and populating the data in the vue instace using ajax calls, the data is coming from my eloquent models.
I have date fields in my model that as default shows the data in the following format: Y-m-d H:i:s. I would like to convert these dates to a more human readable format e.g. d-m-Y when sending the data to my webpage via ajax calls that populate my vue instance. I'm aware of the following ways of accomplishing this:
-
Render at the client end using something like momentjs - I don't think this option is a good idea because the view shouldn't really be doing such work (if it can be avoided) - right?
-
Using something fractal transformer - I have tried to implement this and so far I am failing as the transformer doesn't appear to return the transformed data. This is my code so far that I've been using as a test:
Transformer for my Student model:
<?php
namespace App\Transformers\Models;
use App\Models\Student;
use League\Fractal;
class StudentTransformer extends Fractal\TransformerAbstract
{
public function transform(Student $student)
{
return [
'name' => $student->name,
'birth_date' => date('d-m-Y', strtotime($student->birth_date)),
'start_date' => date('d-m-Y', strtotime($student->start_date)),
'is_active' => $student->is_active ? 'Yes' : 'No',
'course_title' => $student->course_title,
'university_id' => $student->university_id,
'institution_id' => $student->institution_id,
'course_id' => $student->course_id,
];
}
}
Routes file:
Route::get('/', function () {
$student = App\Models\Student::first();
$response = new League\Fractal\Resource\Item($student, new App\Transformers\Models\StudentTransformer);
return response()->json([$response]);
});
- Using a view presenter - I have considered using https://github.com/laravel-auto-presenter/laravel-auto-presenter, but I believe this would only help in passing data to the view, but would not help for ajax calls - right?
Any advice would be appreciated on this! Thanks.