Laravel 9中Accessor与Mutator示例失效问题排查
问题排查:Laravel 9 新写法 Accessor/Mutator 不生效
针对你的问题,按以下步骤逐一排查:
1. 确认Attribute类的命名空间是否正确导入
Laravel 9 的 Attribute 类位于 Illuminate\Database\Eloquent\Casts\Attribute,必须在模型顶部导入该类:
use Illuminate\Database\Eloquent\Casts\Attribute;
如果未导入,PHP会默认查找当前命名空间下的 Attribute 类,导致无法正确实例化,自然不会触发Accessor/Mutator逻辑。
2. 检查模型的可填充字段配置(针对Mutator不生效)
如果保存模型时Mutator未生效,确认 name 字段是否在模型的 $fillable 数组中(或设置 $guarded 为空数组):
protected $fillable = ['name']; // 或者 protected $guarded = [];
若字段不在可填充列表中,赋值时会跳过Mutator处理,直接写入原始值。
3. 清除Laravel缓存
Laravel可能缓存了模型的属性解析信息,执行以下命令清除缓存:
php artisan cache:clear php artisan model:clear
缓存会导致新的Attribute定义无法加载,清除后重新测试即可。
4. 确认模型实例的属性加载逻辑
如果是从已有的查询结果中获取模型,检查是否在查询中使用 select 排除了 name 字段,或通过关联加载导致属性未触发Accessor。
正确示例代码
完整的Tag模型代码参考:
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Casts\Attribute; class Tag extends Model { protected $fillable = ['name']; protected function name(): Attribute { return Attribute::make( get: fn ($value) => strtolower($value), set: fn ($value) => strtolower($value), ); } }
内容的提问来源于stack exchange,提问作者Hardist
相关产品推荐
相关产品推荐

