I’ve been doing some reading of Laravel documentation and I noticed I overlooked learning how to create accessor within data models.

Basically, accessor functions are helper functions defined in models within your your code base.

For example, lets say you have a users model with title, first_name and last_name as string columns within the database. In order to create a string containing the full name of the user, you may find yourself doing the following:

$fullName = $user->title . ' ' . $user->first_name . ' ' . $user->last_name;

To make it shorter, you could do…

$fullName = "{$user->title} {$user->first_name} {$user->last_name}";

or you could do

$user = User::find(1); // Example user call
$fullName = $user->full_name();

How does this work?

As mentioned before, you can define an accessor function within the model file e.g. User.php.

The function starts with the word get followed by the camelCase name you decide to use (In this case it is FullName). It is then closed off with the word Attribute.

<?php

namespace App;

class User extends Model {

...

    public function getFullNameAttribute()
    {
        return ucfirst($this->title) . ' ' . ucfirst($this->first_name) . ucfirst($this->last_name);
    }

}

Once applied, $fullName = $user->full_name(); will return the full name of a user. In this example, the first character of the title, first and last names will be made uppercase.

This is especially good with blade templating when you have long strings to concatenate often. Try this out in your projects if haven’t already!