Home » Source Book » Laravel Accessors With An Example

Laravel Accessors With An Example

Last updated on June 14, 2022 by

In this source book, we will learn what is Laravel Accessors, how to use Laravel Accessors with an example. Let’s explore the Laravel Accessor without wasting a second.

Table of Contents
1. What Are Accessors In Laravel
2. How To Define Accessors
3. Example Of Accessors In Laravel

01 What Are Accessors In Laravel

The Accessor is used to format the attribute values when we retrieve them from the database. Accessor can also be helpful to add custom new columns while selecting records using queries or Eloquent.

02 How To Define Accessors

To define the Accessor, we need to add a method in the relevant model. Let’s say, we want to get the full name of any user from the first_name and last_name columns.

To do that we need to define an accessor method with get{Attribute}Attribute in your model where {Attribute} is the “studly” cased name of the column you wish to access. In our case, we need to get the full name so our {Attribute} will be FullName as per the “studly” case.

So our method name will be getFullNameAttribute() as per our example. Moreover, if we want to achieve path_name then your method name will be getPathNameAttribute(). Let’s now add the method to our model.

03 Example Of Accessors In Laravel

app/Models/User.php

<?php

namespace App\Models;

use App\Notifications\VerifyEmailQueued;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements MustVerifyEmail
{
    protected $fillable = [
        'title', 'first_name', 'middle_name', 'last_name', 'email', 'mobile', 'password'
    ];


    public function getFullNameAttribute() {
        $name = $this->first_name;

        if (!empty($this->middle_name)) {
            $name .= ' '. $this->middle_name;
        }

        if (!empty($this->last_name)) {
            $name .= ' '. $this->last_name;
        }
        return $name;
    }
}

You can see in the above example, by using the $this you can access any column of your model and you can transform it as you like by using the Laravel Accessor.

Now, you can get the full name as below:

use App\Models\User;

$user = User::find(1);

$fullName = $user->full_name;

dd($fullName);

Output:

Scratch Code

You can also transform the first_name with the first upper case character simply using return ucfirst($this->first_name); by defining getFirstNameAttribute(). Isn’t it cool?

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the user's first name.
     *
     * @param  string  $value
     * @return string
     */
    public function getFirstNameAttribute($value)
    {
        return ucfirst($value);
    }
}

If you are creating Accessors for any of the existing column of the database table then you can pass the parameter and transform it as you like or you can also use the $this variable.

That’s it from our end. We hope this article helped you to understand what is Laravel Accessors, how to define Laravel Accessors with examples.

Additionally, read our guide:

  1. Laravel: Pivot Table With An Example
  2. Add Column After A Column In Laravel Migration
  3. Laravel: Change Column Type In Migration
  4. Laravel: Change Column Name In Migration
  5. How To Use Where Date Between In Laravel
  6. How To Add Laravel Next Prev Pagination
  7. Laravel Remove Column From Table In Migration
  8. Laravel: Get Month Name From Date
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Calculate Age From Birthdate
  11. How To Dynamic iFrame URL In Elementor
  12. How To Handle Failed Jobs In Laravel
  13. How To Remove WooCommerce Data After Uninstall
  14. How To Get Latest Records In Laravel
  15. How To Break Nested Loops In PHP Or Laravel
  16. How To Pass Laravel URL Parameter
  17. Laravel Run Specific Migration

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post 🙂 Keep Smiling! Happy Coding!

Leave a Comment