簡體   English   中英

Laravel變量和模型觀察者

[英]Laravel Mutator and Model Observer

我試圖弄清楚如何使用Laravel項目的增幅器將英尺和英寸的兩個表單字段轉換為height屬性。

現在,我收到一個錯誤,提示高度不能為null,所以我想弄清楚為什么未設置高度。

// 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'),
    ]);
}

這不是增幅器的工作方式。 該方法獲得的唯一參數是您在創建或更新時將字段設置為的值。 應該是這樣。

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

在create方法中分配值之前,應先進行英尺和英寸轉換。 在這種情況下,轉換器是無用的。 其次,您需要在模型中設置$fillable fillable屬性,以允許將值分配給正在創建的字段。

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,
    ]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM