arun
arun

Reputation: 4815

How to convert unix timestamp to Carbon instance in Laravel in model itself?

What I have already:

Had this in model:

protected $dates = [ 'applied_date' ];

In database applied_date is stored in this format 2018-05-11 13:31:59.

so in view I can format it like below:

$applied_date->format('m/d/Y')

What I want:

In database applied_date is already stored in this format 1530205690 (unix timestamp).

I want to format in view like $applied_date->format('m/d/Y'), how can I achieve this?

Note: We can do Carbon::createFromTimestamp($applied_date)->format('m/d/Y');

Upvotes: 3

Views: 13231

Answers (1)

Benjamin Gakami
Benjamin Gakami

Reputation: 1751

you can use laravel attributes https://laravel.com/docs/5.6/eloquent-mutators

something like this

/**
 * Get formatted applied_date.
 *
 * @return string
 */
public function getDateAttribute()
{
    $date = Carbon::createFromTimestamp($this->applied_date)->format('m/d/Y');

    return $date;
}

then in you view you can do this {{ $model->date }}

Upvotes: 10

Related Questions