Customizing Attribute Behavior with Eloquent Accessors and Mutators
Owner: SnippetBot
Created: 2026-09-21 00:00:23
Size: 1.30 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// app/Models/User.php
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute; // For Laravel 9+
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class User extends Model
{
protected $fillable = ['first_name', 'last_name', 'email', 'password'];
// Accessor: Get full name (Laravel 9+ using Attribute class)
protected function fullName(): Attribute
{
return Attribute::make(
get: fn (mixed $value, array $attributes) => $attributes['first_name'] . ' ' . $attributes['last_name'],
);
}
// Mutator: Set first name (Laravel 9+ using Attribute class)
protected function firstName(): Attribute
{
return Attribute::make(
set: fn (string $value) => Str::ucfirst($value),
);
}
// Old way (Laravel 8 and below)
// public function getFullNameAttribute(): string
// {
// return $this->first_name . ' ' . $this->last_name;
// }
// public function setFirstNameAttribute(string $value): void
// {
// $this->attributes['first_name'] = Str::ucfirst($value);
// }
}
// Usage examples:
$user = App\Models\User::find(1);
echo $user->full_name; // Accessor
$user->first_name = 'john'; // Mutator
$user->last_name = 'doe';
$user->save();
// In database, first_name will be 'John'