为什么 Laravel 8 突变器不能正常工作?

Why Laravel 8 mutator doesn`t work properly?

我尝试更新模型,但活动的结果始终保持为 0

型号

class GasStation extends Model {
    protected $fillable = ['title', 'active'];    
    public function setActiveAttibute($value){
        $this->attributes['active'] = ($this->attributes['active'] === 'on') ? 1 : 0;
    }

}

控制器方法

public function create(Request $request) {   
        $postContent = $request->all();
        $instance = GasStation::create($postContent);
}

我做错了什么?

你必须使用 $value 变量,$this->attributes['active'] 包含属性的旧值。

class GasStation extends Model {
    protected $fillable = ['title', 'active'];    
    public function setActiveAttibute($value){
        $this->attributes['active'] = ($value === 'on') ? 1 : 0;
    }

}