My blog

posts

Enhancing Eloquent Models: Unveiling the Power of $appends with Accessors in Laravel

Eloquent, the powerful ORM in Laravel, introduces a handy feature known as Accessors, allowing you to define custom fields on top of your existing database table columns. However, the question arises: Should you use the Eloquent property $appends or not, and what exactly sets them apart?

How Accessors Work

For those unfamiliar or in need of a quick reminder, consider a scenario where you have a User model with fields first_name and last_name in the database table. You can create a function in app\User.php like this:

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

This allows you to access the full_name property, which translates to:

echo User::find(1)->full_name;

However, when you convert the User object to JSON, the full_name property won't be included:

dd(User::find(1)->toJSON());

Introducing $appends

Here's the solution: in your User model, you can add the $appends attribute and list the fields that should automatically be appended:

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

Now, the full_name attribute will be automatically added to the JSON output:

{
     "id": 1, 
       "first_name": "John", 
         "last_name": "Doe", 
          "email": "johndoe@gmail.com",
           "created_at": "2023-10-18 08:16:00",
             "updated_at": "2023-10-18 08:18:00", 
                "full_name": "John Doe"
}

In essence, while Accessor fields work by describing getAbcAttribute() methods, if you wish to include them in the returned list, add them to the $appends property. For a more in-depth understanding of Accessors (and related topics like Mutators), refer to the official documentation.

260 Laravel February 18, 2024 1 comments

1 Comments

  • Sahi hi bro!!

    Reply

Add a comment