Laravel Accessors
1 min read

Laravel Accessors

A common use case in Laravel projects is needing an altered or calculated value from the data you are storing. I ran into this use case in my project dotnetjobs.dev, where I wanted to display the amount of days it had been since a job was posted on the board.

My jobs table stored the created date, so I wanted to drive the days since posted attribute off of that.

Using Laravel Accessors on my jobs model, that was easily accomplished. Per the official Laravel docs, setting a function in your model with the format get{Attribute}Attribute will make the accessor available.

public function getDaysSinceCreatedAttribute()
{
    $now = Carbon::now();
    $diff = $this->created_at->diffInDays($now);
    if ($diff == 0)
    	return 'Today';
    return $diff . 'd';
}

Now anytime I have an instance of my jobs model, i can call the accessor like this:

$job->days_since_created

Coming from CakePHP, I was used to using virtual fields to accomplish this. It was nice to see similar functionality in Laravel.