2017-05-29 202 views
0

我想弄清楚如何使用我的Laravel项目的增变器将脚和英寸的两个表单域转换为高度属性。Laravel Mutator和模型观察者

现在我得到一个错误,高度不能为空,所以我试图找出为什么它没有被设置。

// Model 

/** 
* Set the height field for the user. 
* 
* @param $feet integer 
* @param $inches integer 
* @return integer 
*/ 
public function setHeightAttribute($feet, $inches) 
{ 
    return $this->attributes['height'] = $feet * 12 + $inches; 
} 

// Observer 

/** 
* Listen to the User created event. 
* 
* @param User $user 
* @return void 
*/ 
public function created(User $user) 
{ 
    $user->bio()->create([ 
     'hometown' => request('hometown'), 
     'height' => request('height'), 
    ]); 
} 

回答

0

这不是变异因子的工作方式。该方法获得的唯一参数是您在创建或更新时设置字段的值。所以它应该是。

public function setHeightAttribute($value) 
{ 
    return $this->attributes['height'] = $value; 
} 

在分配create方法中的值之前,应该执行英尺和英寸转换。在这种情况下,增变器是无用的。其次,您需要在模型中设置$fillable propery,以允许将值分配给正在创建的字段。

protected $fillable = [ 
    'hometown', 'height', 
]; 

从您的错误判断,看起来您正在传递请求输入中的英尺和英寸值。你可以做这样的事情。将输入字段名称替换为您使用的实际名称。

public function created(User $user) 
{ 
    $hometown = request('hometown'); 
    $height = (request('feet', 0) * 12) + request('inches', 0); 

    $user->bio()->create([ 
     'hometown' => $hometown, 
     'height' => $height, 
    ]); 
}