Laravel 新旧版本模型属性访问器、修改器的选用

Laravel 9 之前模型属性访问器、修改器

通过 setFooBarAttribute($value)getFooBarAttribute() 方法来定义和访问自定义动态 fooBar 属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
/**
* 设置用户的名字
*/
public function setFirstNameAttribute($value)
{
$this->attributes['first_name'] = strtolower($value);
}

/**
* 获取用户的全名
*/
public function getFullNameAttribute()
{
return "{$this->first_name} {$this->last_name}";
}
}

Laravel 9 及之后版本的模型属性访问器、修改器

通过返回值类型为 Attribute 类来定义和访问自定义动态属性。

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
namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
/**
* 设置、访问用户的名字
*/
protected function firstName(): Attribute
{
return Attribute::make(
get: fn (string $value) => ucfirst($value),
set: fn (string $value) => strtolower($value),
);
}

/**
* 获取用户的全名
*/
protected function fullName(): Attribute
{
return Attribute::make(
get: fn () => "{$this->first_name} {$this->last_name}";
);
}
}

访问的异同

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
use App\Models\User;

$user = User::find(1);

# 相同点:都可以用 foo_bar 的动态变量访问
$user->first_name = 'a m';
$firstName = $user->first_name;
$fullName = $user->full_name;

# 不同点:旧版的 setFooBarAttribute、getFooBarAttribute 不管下划线和大小写,都会重写到对应方法
# 而新版则只允许小写加下划线的变量名访问。
$user->firstName = 'a m';
$user->FirstName = 'a m';
$user->First_Name = 'a m';
$user->fir_st_na_me = 'a m';
$firstName = $user->First_Name;
$fullName = $user->FUllNamE;

因旧版的访问变量名很随意,会导致变量名不统一引起问题,因此建议使用新版的方式。

比如:

1
$user->append(['firstName', 'Full_Name']);

返回给前端的json将是:

1
2
3
4
{
"firstName": 'a m',
"Full_Name": 'a m xxx'
}

前端小哥哥天天哭着跟你说:大哥,这个变量名怎么又不对了呀?
别跟我说你们前端没天天这个人。

Laravel 新旧版本模型属性访问器、修改器的选用

https://coderpan.com/php/laravel/attribute-mutator.html

作者

CoderPan

发布于

2024-05-08

更新于

2024-05-08

许可协议

评论