Neha
Neha

Reputation: 2261

I want to add a custom attribute to model in laravel

I need to add an extra attribute to my laravel model without using get Attribute. i want to get created_at attribute in both default and custom format.

default : created_at : 2018-07-25 15:38:56

second: 10 Days Ago 

if i use getCreatedAtAttribute() it changes the default attribute.

Upvotes: 7

Views: 16332

Answers (1)

SteD
SteD

Reputation: 14027

In your model, add this:

protected $appends = ['readable_created_at'];

public function getReadableCreatedAtAttribute()
{
    return $this->created_at; //or however you want to manipulate it
}

After which, you can access it like normal, e.g. $user->readable_created_at.

Read more at the Laravel Doc here.

Upvotes: 12

Related Questions