How to Add Custom Attribute in Laravel Model?

By Hardik Savani November 5, 2023 Category : Laravel

Hi,

I will explain step by step tutorial how to add attribute in laravel model. you'll learn laravel append attribute to model. It's a simple example of laravel append value to model. This article goes in detailed on custom attribute in laravel model. Let's see below example laravel append attribute to model.

If you want to set custom attributes in laravel model, then I will help you. I will give you two simple examples of append attributes to model and access it. In this example, we have user table with first_name and last_name columns. we will create full_name custom attribute and access it with user object.

Let's see one by one example:

Example 1: Laravel Model Define Attribute

app/Models/User.php

<?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;

....

/**

* Determine full name of user

*

* @return \Illuminate\Database\Eloquent\Casts\Attribute

*/

public function getFullNameAttribute()

{

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

}

}

Access Attribute:

$full_name = User::find(1)->full_name;

Output:

Hardik Savani

Example 2: Laravel Model Define Attribute with Append Property

Using $appends property, you will get always "full_name" with user model object.

app/Models/User.php

<?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 accessors to append to the model's array form.

*

* @var array

*/

protected $appends = ['full_name'];

/**

* Determine full name of user

*

* @return \Illuminate\Database\Eloquent\Casts\Attribute

*/

public function getFullNameAttribute()

{

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

}

}

Access Attribute:

$user = User::find(1);

Output:

Array

(

[id] => 1

[first_name] => Hardik

[last_name] => Savani

[email] => aatmaninfotech@gmail.com

[created_at] => 2022-05-23T12:58:18.000000Z

[updated_at] => 2022-05-23T12:58:18.000000Z

[full_name] => Hardik Savani

)

I hope it can help you...

Tags :
Shares