Many times you want the first_name or last_name to be capitalized while storing in your database. And sometimes you want to stored status like open/closed with a small case and when fetching you need to be capitalized.

This is easily achievable in Laravel and has feature named Accessors (What to do when accessing some field) & Mutators (What to do when saving/updating some field).


Prerequisites

I hope you have basic understanding of Laravel & know how to do CRUD (Create, Read, Update, Delete) operations.


Accessors (getColumnNameAttribute)

To define an accessor, create a **getFirstNameAttribute** method on your model where FirstNameis the “studly” cased name of the column you wish to access, here its **first_name** as stored in your database table. This accessor will automatically called by Eloquent when you retrieve the value of the first_name from database table.

NOTE: Accessor starts with **get** and ends with **Attribute**. In between you will have column name in studly caps.

Following is the example of how to do it in MODEL

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
  public function getFirstNameAttribute($firstName)
  {
    return ucfirst($firstName);
  }
}

In the above example you can see that the **$firstName** attribute is passed and its returning capitalized name. You can name anything to your accessor method parameter.

In Controller

$user = App\Models\User::where('email', $email)->first();
/** Here the FirstName accessor is called automatically */
echo $user->first_name; 

You can also user accessor to return the value based on more than one fields. For example

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

#database #capitalized

 Problem In Set Attribute While Saving/Updating Data & How To Resolve It
1.05 GEEK