2017-05-29 49 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, 
    ]); 
}