2

I have a Message model like this :

class Message extends Model
{
    protected $primaryKey = 'message_id';
    protected $dates      = ['created_at', 'updated_at', 'receiver_deleted_at', 'sender_deleted_at', 'sender_read_at', 'receiver_read_at'];
}

As you can see there are some date fields that hold dates as DATETIME(YYYY-MM-DD HH:MM:SS) format.

But I want when get an instance of model all date fields convert to unix-timestamp format and then return.

I know that can use accessor like this for every field :

public function getCreatedAtAttribute()
{
    dd(strtotime($this->attributes['created_at']));
    return strtotime($this->attributes['created_at']);
}

But in this case I must define a function like above for each field.

But I want an easier way that force model to return date fields as unix-timestamp format.

2
  • Accessors take care of the conversion to a Carbon instance which is an extension of default DateTime. So, $this->created_at->format('U'); should work. Commented Apr 22, 2017 at 11:36
  • @TomLank., I want when call an instance of model converted format returned Commented Apr 22, 2017 at 11:39

2 Answers 2

10
protected $casts = [
    'created_at' => 'timestamp',
    'updated_at' => 'timestamp'
];

In model just add these cast to get unix timestamp

Sign up to request clarification or add additional context in comments.

Comments

1

You can override the :

protected function getDateFormat()
{
 return 'U';
}

OR

Use timestamp property for each column:

$model->created_at->timestamp

Reference: https://laravel.com/docs/4.2/eloquent#timestamps

1 Comment

I added getDateFormat function but got this error : Trailing data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.