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

ultrasamad's avatar

How to change created_at to a timestamp during or after querying.

I have my data in this form:

$data = Notice::find(1)->first();

What I want to achieve is to convert the created_at attribute value in this object to a timestamp. I know I could override the $dateFormat attribute in my model to get a custom value in my db. However, I want to only customize it when retrieving the result. Is there a way to format the column during querying or better still modify just the created attribute to be a timestamp without necessarily duplicating objects here and there?

Thanks!

0 likes
6 replies
abusalameh's avatar

@ULTRASAMAD

you need to define it in the model as a date and you can use Acessor to get the data back as you want

<?php 

class Notice extends Eloquent {

protected $dates = ['created_at', 'updated_at'];


public function getCreatedAtAttribute($value)
    {
    // example 
    return $value->diffForHumans();

    }

}

https://laravel.com/docs/5.4/eloquent-mutators

1 like
ultrasamad's avatar

@abusalameh Thanks. But if I do that, it will means I will be storing a different date time format in my database. I want to maintain the default datetime but only format the created_at of the data returned after the query.

Snapey's avatar

what? it is a timestamp

and it is returned as a Carbon object so it can be in whatever form you want when you use it

btw any time you call a variable $data, grab one hand with the other and whack it across your face.

ultrasamad's avatar

Sorry, I thought my question was clear enough. I was actually looking for a way to format one of the field or attribute of my data object during the querying process. It seems to me there is nothing like that, so I'm now falling back to way of mutating the object containing my data without necessarily looping through this object.

Something like

$data->created_at = $data->created_at->timestamp; //from carbon

so that my new data object will have something like:

created_at => 1497726118 //as a value

instead of:

created_at => '2017-06-17 19:01:58';

without touching my model, as in overriding attributes.

Snapey's avatar

You could create an accessor with a different name?

public function getCreated_timestampAttribute()
{
    return $this->created_at->timestamp();
}

and then you would have a choice of created_at and created_timestamp elements in json for instance.

If casting the object to an array, or json, use the $appends attribute to automatically add the new value

Please or to participate in this conversation.