Monday, 16 October 2023

Optimizing Laravel Models: How to Append Custom Attributes

You can easily add attributes to a model in Laravel's Eloquent ORM that aren't in the database but can be made from existing attributes. People often call these "accessors."

This is how to use an accessor to add an attribute to a model:

  1. What is an Accessor?

In Laravel, you can define an accessor by making a method on your Eloquent model that follows this naming pattern:

get<AttributeName>Attribute


In this case, <AttributeName> should be in StudlyCase format. Laravel will automatically change it to this format when you access the attribute in your code. 

For example:

Let's say you want to add a full_name property to your User model. You would say the accessor is: 


namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    // Accessor to get the full name
    public function getFullNameAttribute()
    {
        return $this->first_name . ' ' . $this->last_name;
    }
}

The getFullNameAttribute method in this case combines the first_name and last_name attributes and returns the result as full_name.

2. Use the $appends Property:

When you convert a model to an array or JSON, accessors are not included by default. You need to add your custom attribute to the $appends property of your model to make sure it shows up in these representations.

class User extends Model {
    protected $appends = ['full_name'];

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

When you add full_name to $appends, you can be sure that your derived attribute will always show up next to the database columns when the model is serialized.

Getting to the Appended Attribute

You can access the custom attribute like any other property of the model once the accessor and $appends property are set up:

$person = User::find(1);
echo $user->full_name; // Results: John Doe

The appended attribute is also automatically added when you change the model to an array or JSON:

$userArray = $user->toArray();
print_r($userArray);

This is especially helpful for APIs or front-end apps that need JSON responses from your Laravel backend.

Advantages of Using Accessors

  1. Dynamic Computation: Create attributes on the fly without changing the way your database is set up.

  2. Cleaner Code: Don't use the same formatting or concatenation logic in controllers or views over and over again.

  3. API Friendly: You can add attributes to JSON responses, which makes front-end development easier.

  4. Reusable: You can use accessors in any part of your app where the model is used.

Best Practices for Accessors

  • Keep them light: Don't do heavy calculations in accessors because they will run every time the attribute is accessed.

  • Use camelCase to name things. The method uses StudlyCase, but Laravel automatically changes it to snake_case when you access it.

  • Only add attributes that are needed: When you add an attribute, it is included in serialization, which can make APIs' payloads bigger.

To sum up

Laravel's Eloquent ORM makes it easy and powerful to work with database records. You can easily add custom attributes to your models without changing your database by using accessors and the property. This approach enhances code readability, simplifies API responses, and allows for dynamic data manipulation.

Whether you’re building a RESTful API, a web application, or an admin dashboard, using accessors to append attributes like full_name in your A User model can streamline your workflow and improve data handling.

No comments:

Post a Comment

.htaccess not working even though allowoverride is enabled

You're not the only one who has had the annoying problem with Apache where your file doesn't work even after you enable it. You'...