Laravel 7/6 Eloquent Accessors and Mutators Example

10-Apr-2023

.

Admin

Laravel 7/6 Eloquent Accessors and Mutators Example

Hi guys,

In this blog,we will explain eloquent accessors and mutators in laravel 7/6. i can show easy show example of eloquent accessors and mutators.

Accessors and mutators allow you to format Eloquent attribute values when you retrieve or set them on model instances. For example, you may want to use the Laravel encrypter to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Eloquent model.

You will following example of eloquent accessors and mutators.

Create Eloquent Accessors and Mutators


here you can easy to create accessors and mutators in model

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;

use Illuminate\Foundation\Auth\User as Authenticatable;

use Illuminate\Notifications\Notifiable;

use Carbon\Carbon;

class User extends Authenticatable

{

use Notifiable;

/**

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = [

'first_name','last_name', 'email', 'password','birth_date',

];

/**

* The attributes that should be hidden for arrays.

*

* @var array

*/

protected $hidden = [

'password', 'remember_token',

];

/**

* The attributes that should be cast to native types.

*

* @var array

*/

protected $casts = [

'email_verified_at' => 'datetime',

];

/**

* Set the user's first name.

*

* @param string $value

* @return void

*/

public function getFullNameAttribute($value){

return ucfirst($this->first_name) . ' ' . ucfirst($this->last_name);

}

/**

* Set the user's first name.

*

* @param string $value

* @return void

*/

public function getAgeAttribute($value)

{

return Carbon::parse($this->birth_date)->age;

}

/**

* Set the user's first name.

*

* @param string $value

* @return void

*/

public function setFirstNameAttribute($value)

{

$this->attributes['first_name'] = strtolower($value);

}

}

Use Accessors and Mutators

<!DOCTYPE html>

<html>

<head>

<title>Laravel 7/6 Eloquent Accessors and Mutators Example - nicesnippets.com/</title>

<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.css">

</head>

<body>

<div class="container">

<div class="row justify-content-center">

<div class="col-md-8">

<div class="card mt-5">

<div class="card-header">Laravel 7/6 Eloquent Accessors and Mutators Example - nicesnippets.com</div>

<div class="card-body">

<ul>

@foreach($users as $key=>$value)

<li>FullName: {{ $value->fullName }}</li>

<li>Age: {{ $value->age }}</li>

@endforeach

</ul>

</div>

</div>

</div>

</div>

</div>

</body>

</html>

It will help you..

#Laravel 7

#Laravel

#Laravel 6