2017-05-07 69 views
3

我有一個CategoryRequest.php文件和一個唯一的字段'name'驗證。 當我使用表單創建時,它可以工作,因此它可以防止插入具有相同名稱的類別。忽略更新時的唯一驗證ID

問題是,當試圖更新它,說:'名稱已被採取。'或者如果我嘗試下面的代碼,它會說:'Undefined Variable:id'。

如何更新,驗證時忽略自己的名字? 這裏是我的代碼:

<?php 

namespace App\Http\Requests; 

use Illuminate\Foundation\Http\FormRequest; 

class CategoryRequest extends FormRequest 
{ 
    /** 
    * Determine if the user is authorized to make this request. 
    * 
    * @return bool 
    */ 
    public function authorize() 
    { 
     return true; 
    } 

    /** 
    * Get the validation rules that apply to the request. 
    * 
    * @return array 
    */ 
    public function rules() 
    { 
     return [ 
      'name' => 'required|unique:categories,name,'.$id.',id' 
     ]; 
    } 
} 

回答

1

改變這一點:

return [ 
    'name' => 'required|unique:categories,name,'.$id.',id' 
]; 

這樣:

return [ 
    'name' => 'required|' . Rule::unique('categories')->ignore('category') 
]; 

或本:

return [ 
    'name' => ['required', Rule::unique('categories')->ignore('category')] 
];