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


留言

這個網誌中的熱門文章

[Android] 筆記 手機上測試自己的 APP

解決fatal: Not a git repository (or any of the parent directories): .git錯誤

[Android 筆記] 設定 ImageView 的圖檔來源