2016年4月25日 星期一

Laravel update form 如果是 Unique 欄位驗證檢查如何排除當下更新的該筆記錄

use laravel 5.

when we update an form, example: "member" table.
and we want the email field should be unique on this table.



so.. maybe our create form request like:
---------------------------------------------------------------------------------
class CreateFormRequest extends FormRequest
{
    public function rules()
    {
        return [
            'email' => 'required|unique:users,email|email',
        ];
    }
}
---------------------------------------------------------------------------------

BUT, when we update, and the email keep "unique", what happened?
also user didn't change his/her email, will still got "the email already exists" error.

so, we need to add some validation rule on out UpdateFormRequset:

---------------------------------------------------------------------------------
class UpdateFormRequest extends FormRequest
{
    public function rules()
    {
        return [
            'email' => 'required|unique:users,id,'. $this->id,
        ];
    }
}
---------------------------------------------------------------------------------
we can exclude the member itself's email unique check by using: unique:users,id,'. $this->id , even if the user didn't change his/her email.

just FYI. :P



Reference:
https://laravel.com/docs/5.1/validation
Laravel 5 Validation Request, how to handle validation on update?
http://stackoverflow.com/questions/22405762/laravel-update-model-with-unique-validation-rule-for-attribute


沒有留言:

張貼留言

若你看的文章,時間太久遠的問題就別問了,因為我應該也忘了... XD

Vue multiselect set autofocus and tinymce set autofocus

要在畫面一進來 focus multiselect 的方式: 參考: https://jsfiddle.net/shentao/mnphdt2g/ 主要就是在 multiselect 的 tag 加上 ref (例如: my_multiselect), 另外在 mounted...