How To

How to Add Custom Attributes in Laravel Model?

Hello Laravel Friends,

In this blog, we are learning how to add a custom attribute in the Laravel model. In this blog, we are going through the example of custom attributes.

What are the Use Cases of Custom Attributes in Laravel?

When we need,

  • some extra information / some calculation logic in the model
  • we need to process the model data
  • get relational data with the model object

In all the above cases, we can use a custom attribute in Laravel.

Letโ€™s take one example of it.

Example of Custom Attribute in Laravel

Here we have one fresh Laravel project. Also, we have a User model with first_name, last_name, email, and password. Here we need to display the userโ€™s full name in our view. So need to create a custom attribute for it. We are creating the full_name attribute in the User model.

Now, your app/Models/User.php file looks like the below.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */    protected $fillable = [
        'first_name',
        'last_name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

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

To access your custom attribute using the model object.

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

Output:ย 

Magecomp Laravel

Suppose you need a full_name attribute with a User model object. You can achieve that using the $appends property of the model class. Please add the following code to your User model.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    โ€ฆ

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */    protected $appends = [
        'full_name'
    ];

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

Now access your custom attribute using the User model object.

return User::find(1);

Output:

{
    first_name: 'Magecomp',
    Last_name:  'Laravel',
    email : 'johndoe@gmail.com',
    email_verified_at : null,
    created_at: '2023-02-15 06:10:20',
    updated_at:  '2023-02-15 06:10:20',
    full_name: 'Magecomp Laravel'
}

Conclusion:

Hence, using the above method, you can easily Add a Custom Attribute in Laravel Model. For any doubts or queries, freely leave a comment, and I will be prompt to answer them. For any customization requirements of your Laravel project, Hire Laravel Developer. Share the tutorial with your other Laravel friends, and stay in touch with us to learn more about Laravel.

Happy Coding!

Click to rate this post!
[Total: 9 Average: 4]
Bharat Desai

Bharat Desai is a Co-Founder at MageComp. He is an Adobe Magento Certified Frontend Developer ๐Ÿ… with having 8+ Years of experience and has developed 150+ Magento 2 Products with MageComp. He has an unquenchable thirst to learn new things. On off days you can find him playing the game of Chess โ™Ÿ๏ธ or Cricket ๐Ÿ.

Recent Posts

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

1 day ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

1 day ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

2 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

3 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

5 days ago

How Upcoming Cookie Changes Will Affect Your E-commerce Website?

The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…

5 days ago