DEV Community

Arman Hasan
Arman Hasan

Posted on

Laravel Accessors And Mutators

Hello artisans how's everything going? Working with Laravel Eloquent ORM we often need to change or format the behavior of data. Accessors and Mutators simply changed the format or the behavior of the data while retrieving and storing. We'll see simple examples to understand these concepts easily

Table Of Contents

  1. Setup Project & Model
  2. Accessors
  3. Mutators
  4. Database Seeder
  5. Route & Controller
  6. Overview

Setup Project & Model

To start the example we need to install and set up the model and database connection first. I'm using phpMyAdmin (MySQL database).

To create a fresh Laravel application run this command in terminal

composer create-project laravel/laravel demoapp
Enter fullscreen mode Exit fullscreen mode

now we have a fresh Laravel application. I already created a database in PHPMyAdmin now go in the .env file to set the database connection

Enter fullscreen mode Exit fullscreen mode


Accessors is a get attribute in Laravel when getting data in a changed or dummy formatted attribute we use an accessor. Suppose we have User model with data table columns with first_name & last_name.


use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
    public function up()
        Schema::create('users', function (Blueprint $table) {

    public function down()
Enter fullscreen mode Exit fullscreen mode

Now we want a full_name attribute to concatenate both first_name and last_name to get full_name. let's see an example for a clear understanding

Go to the app\Models\Users.phpfile and write the Assessor method

Syntext For Accessors

protected $fillable = [

// Accessor Method
public function getPhoneAttribute() {
     return $this->phone_code . "-" . $this->phone_number;
Enter fullscreen mode Exit fullscreen mode


Mutator is a setter value attribute that transforms an Eloquent attribute value when it is set into the database. To get an example lets again go back to app\Models\Users.php to write a mutator method

Syntext For Mutators

// Mutator Method
public function setNameAttribute($value)
   return $this->attributes['name'] = ucfirst($value);
Enter fullscreen mode Exit fullscreen mode

We are trying to convert the first character of a name string to uppercase that's why using the ucfirst() function to transform the data while storing.

Database Seeder

To test our methods we need to have some data in our database. Using seeder to create data for example

In the database/factories/UserFactory.php file write this factory seeder

public function definition()
       return [
           'name' => $this->faker->name(),
           // this will create 3 digit random numbers
           'phone_code' => $this->faker->numerify('###'),
           // this will create 10 digit random numbers
           'phone_number' => $this->faker->numerify('##########'),
           'email' => $this->faker->unique()->safeEmail(),
           'email_verified_at' => now(),
           'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
           'remember_token' => Str::random(10),
Enter fullscreen mode Exit fullscreen mode

Now need to add this in database/factories/DatabaseSeeders.php

class DatabaseSeeder extends Seeder
    public function run()
Enter fullscreen mode Exit fullscreen mode

Route & Controller

In the web.php route file add this route to view the welcome page


use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Controller;

Enter fullscreen mode Exit fullscreen mode

In app/Http/Controllers/Controller.php write this function

public function index()
        $data = User::all();
        return view('welcome')->with('data',$data);
Enter fullscreen mode Exit fullscreen mode

This function will fetch all the data from the User Model in welcome.blade.php

Blade File

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Demo App</title>
        <link href=";600;700&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
        <div class="container">
            <div class="row">
                <div class="card shadow p-3 mb-5 mt-5 bg-white rounded mx-auto">
                    <div class="">
                        <table class="table table-striped table-dark">
                                <th scope="col">#</th>
                                <th scope="col">Name</th>
                                <th scope="col">Phone</th>
                                @foreach ($data as $d)
                                <td>{{ $loop->iteration }}</td>
                                <td>{{ $d->name }}</td>
                                <td>{{ $d->phone }}</td>
Enter fullscreen mode Exit fullscreen mode


Final Output

This is our welcome.blade.php file where we can see data formations are changed according to the User.php model Accessors and Mutators methods. we are getting the phone_code and phone_number into phone attribute call. also, we are getting the names in formatted order.

Thats all stay tuned

Top comments (0)