Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

haakym's avatar

Best practice for date conversion for view data/data from ajax

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:

  1. 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?

  2. 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]);

});
  1. 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.

0 likes
7 replies
milon's avatar

As you are dealing with Student object just declare birth date and start date as date field in model.

class Student
{
    protected $dates = ['birth_date', 'start_date'];

    //other codes
}

then it will be a Carbon object. so in the transformer you can do like this-

'birth_date'     => $student->birth_date->toDateString(),
'start_date'     => $student->start_date->toDateString()
haakym's avatar

@milon my issue is not how to convert dates, I'm quite comfortable with doing that, but my issue is how to get the transformer working.

Right now it's returning an empty response! Any ideas why the fractal transformer isn't working?

joedawson's avatar

What's not working with your transformer? (By the way, you didn't mention that your transformer wasn't working in your original post.)

Have you tried to dd() the $response?

haakym's avatar

Yes sorry about that I failed to mention that properly.

If I run the following code:

Route::get('/', function () {

    $student = App\Models\Student::first();

    $response = new League\Fractal\Resource\Item($student, new App\Transformers\Models\StudentTransformer);

    dd($response);

});

I get this:

Item {#299 ▼
  #data: Student {#305 ▼
    #fillable: array:10 [▶]
    #connection: null
    #table: null
    #primaryKey: "id"
    #perPage: 15
    +incrementing: true
    +timestamps: true
    #attributes: array:13 [▶]
    #original: array:13 [▶]
    #relations: []
    #hidden: []
    #visible: []
    #appends: []
    #guarded: array:1 [▶]
    #dates: []
    #dateFormat: null
    #casts: []
    #touches: []
    #observables: []
    #with: []
    #morphClass: null
    +exists: true
  }
  #meta: []
  #resourceKey: null
  #transformer: StudentTransformer {#301 ▼
    #availableIncludes: []
    #defaultIncludes: []
    #currentScope: null
  }
}
joedawson's avatar

No problem, just making you aware in case you needed to update your reply :)

Looks like it's transforming fine - so you're saying when you visit your / route, it just returns nothing? Is it null or just a blank screen?

haakym's avatar

Yes, thank you. Have updated the question to indicate it's not working.

If I return it in a response like so:

Route::get('/', function () {

    $student = App\Models\Student::first();

    $response = new League\Fractal\Resource\Item($student, new App\Transformers\Models\StudentTransformer);

    return response()->json([$response]);

});

I get:

[
    { }
]

What makes you think the transforming is fine? Where is the transformed data supposed to reside in the return transformed object? In the dd() code in my last post the original eloquent model is sitting in Item->data and the data is all the same, no transformations. I'm clearly missing something here!

Thanks for your input so far @JoeDawson most appreciated

haakym's avatar

A question I asked on Stackoverflow got a working answer for me, code:

Route::get('/', function () {

    $student = App\Models\Student::first();

    $response = new League\Fractal\Resource\Item($student, new App\Transformers\Models\StudentTransformer);

    $manager = new \League\Fractal\Manager();
    $manager->setSerializer(new \League\Fractal\Serializer\ArraySerializer());

    return response()->json($manager->createData($response)->toArray());

});

Link: http://stackoverflow.com/questions/34017140/transform-eloquent-model-using-fractal

Please or to participate in this conversation.