Monday, 16 October 2023

Optimizing Laravel Models: How to Append Custom Attributes

In Laravel's Eloquent ORM, you can easily append attributes to a model that don't exist in the database but can be derived from existing attributes. These are often called "accessors."


Here's how to append an attribute to a model using an accessor:


  1. Define an Accessor:

To define an accessor, create a get<AttributeName>Attribute method on your model where <AttributeName> is the studly cased name of the column you wish to access.


    2. Use the $appends Property:

If you want the attribute to be included in the model's array or JSON representation, you should add it to the $appends property on the model.


Example:

Suppose you have a User model with first_name and last_name columns in the database, but you want to easily retrieve the user's full name.


namespace App\Models;


use Illuminate\Database\Eloquent\Model;


class User extends Model

{

    // Attributes to be appended to the model's array or JSON representation

    protected $appends = ['full_name'];


    // Accessor to get the full name

    public function getFullNameAttribute()

    {

        return $this->first_name . ' ' . $this->last_name;

    }

}

Now, when you convert a User model instance to an array or JSON, it will include the full_name attribute:

$user = User::find(1); return $user->toArray();


output

[
 'id' => 1, 
'first_name' => 'John', 
'last_name' => 'Doe', 
'full_name' => 'John Doe', 
// ... other attributes ... 
]

Remember, accessors will not affect how data is stored in your database, only how it's represented when you access it using Eloquent.


No comments:

Post a Comment

Laravel csrf token mismatch for ajax post request

Error "CSRF Token Mismatch" commonly occurs if tokens do not match in both sessions and sent , and received requests.CSRF token he...