Laravel Model: How to Add a Custom Attribute

Hello Geek ,In Laravel models represent the database tables in your application. Models allow you to interact with the database tables and perform operations like creating, reading, updating, and deleting records.

One of the great things about Laravel is its flexibility, and you can add custom attributes to your models. Custom attributes are not part of the database schema, but they allow you to attach additional information to the model instance that can be accessed like any other attribute. In this guide, we will show you how to add custom attributes to a Laravel model.

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:

About the nerd

Example 2: Laravel Model Define Attribute with Append Property

<?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] => About

    [last_name] => The Nerd

    [email] => info@aboutthenerd.com

    [created_at] => 2023-01-31T07:00:00.000000Z

    [updated_at] => 2023-01-31T07:49:00.000000Z

    [full_name] => About the nerd

)

All the best nerd!

Leave a Reply