Laravel Fact – Make computed attributes for Eloquent models

0
300
Make computed attributes for Eloquent models
Make computed attributes for Eloquent models

Beside auto-generated attributes mapping from database schema, Laravel also provides developers ability to make computed attributes for Eloquent models.

Make computed attributes for Eloquent

To state the problem, let’s take a look at this User model:

class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'email', 'password', 'first_name', 'last_name'
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

}

As you can see, there are two fields for user name, in specific, they are first_name and last_name.

To access those names’ attributes, just call it directly like: $user->first_name, $user->last_name.

Okay, nothing special.

But when you need to, for example, display user’s full name, you can do by concatenation them, so it would be $user->first_name.' '.$user->last_name.

Wait, what if you need to display full name in many places in your app?

Alright, the DRY comes into handy.

Create a new method

Obviously, newly-Laravel developers will do this way.

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

Well, there is absolutely nothing wrong with this approach. It is indeed correct!

However, since this is pretty much a common operation, Laravel has provided such a cool method to handle this.

Create a computed attribute

Generally, computed attribute is the value made up from other attributes. Apparently, in this case, full name is a computed attribute because it is made from the concatenation of first name and last name attributes.

In Laravel, computed attribute is supported for only Eloquent mode, that is, any child derived from Illuminate\Database\Eloquent\Model class.

You need to follow convention when creating computed attributes.

public function getXXXAttribute() {
    return YYY; 
}

where:

  • XXX : is the attribute name in Pascal-case.
  • YYY : well, attribute you want to return.

You are free to do all necessary computation and calculation inside the computing method.

To access the computed attributes, you will access the XXX in snake case.

Update our code with full name computed attribute:

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

To access the full name attribute, you just access like a regular attribute, $user->full_name.

That’s all you have to do.

Summary

Computed attribute is a great addition to Laravel Eloquent model. It makes the code clean and very DRY.

But wait, didn’t I mention where this fact is on Laravel documentation?

It is here, Laravel Eloquent – Accessors & Mutators.