如何验证在Laravel中更新它的用户的唯一电子邮件?

时间:2016-12-02 23:23:49

标签: laravel validation authentication

我正在使用Laravel 5.2并希望使用验证器更新用户的帐户。

我希望保持电子邮件字段的唯一性,但是,如果用户输入他当前的电子邮件,它将会中断。如果电子邮件是唯一的,除了用户自己当前的电子邮件外,我该如何更新?

8 个答案:

答案 0 :(得分:11)

在Request Class中,您可能需要在PUT或PATCH方法中进行此验证,如果您没有用户,那么您可以简单地使用此规则

 You have 2 options to do this

1:

 'email' => "unique:users,email,$this->id,id"

OR

2:

 use Illuminate\Validation\Rule; //import Rule class 
'email' => Rule::unique('users')->ignore($this->id); //use it in PUT or PATCH method

<强> $这 - &GT;编号 正在提供用户的id,因为 $ this 是Request Class的对象,Request也包含用户对象。

public function rules()
{
    switch ($this->method()) {
        case 'POST':
        {
            return [
                'name' => 'required',
                'email' => 'required|email|unique:users',
                'password' => 'required'
            ];
        }
        case 'PUT':
        case 'PATCH':
        {
            return [
                'name' => 'required',
                'email' => "unique:users,email,$this->id,id",
                                   OR
                //below way will only work in Laravel ^5.5 
                'email' => Rule::unique('users')->ignore($this->id),

               //Sometimes you dont have id in $this object
               //then you can use route method to get object of model 
               //and then get the id or slug whatever you want like below:

              'email' => Rule::unique('users')->ignore($this->route()->user->id),
            ];
        }
        default: break;
    }
}

希望它能在使用请求类时解决问题。

答案 1 :(得分:1)

在Laravel 5.7上,指示验证程序忽略用户的ID,我们将使用Rule类来流畅地定义规则。在此示例中,我们还将验证规则指定为数组,而不是使用|分隔规则的字符:

use Illuminate\Validation\Rule;

Validator::make($data, [
    'email' => [
        'required',
         Rule::unique('users')->ignore($user->id),
    ],
]);

答案 2 :(得分:1)

对于使用FormRequest和Laravel 5.7并面对此问题的编码人员,您可以执行以下操作

public function rules() {

    return [
        'email' => ['required', 'string', 'email', 'max:255',
            Rule::unique('users')->ignore($this->user),
        ],
    ];

}

$this->user将返回来自请求的用户ID。

答案 3 :(得分:0)

创建表单请求并将此代码添加到App / Http / Request / YourFormRequest类

public function rules()
{  // get user by uri segment
   $user = User::find((int) request()->segment(2)); 
   return [ 
        'name' => 'required|string|max:100', 
        'email' => 'required|email|unique:users,email,'.$user->id.',id' 
    ];
}

检查文档here

答案 4 :(得分:0)

在Laravel 7上构建API时,如果您想要干净的东西,可以简单地使用:

public function rules()
{
    $emailRule = Rule::unique((new User)->getTable());

    if (request()->isMethod('put')) {
        // we update user, let's ignore its own email
        // consider your route like : PUT /users/{user}
        $emailRule->ignore($this->route('user'));
    }

    return [
        'name' => 'required',
        'email' => [
            'required',
            'email',
            $emailRule
        ],
    ];
}

您可以获取要更新的用户(在此处使用PUT方法)而忽略他。

答案 5 :(得分:0)

为了更新用户的帐户,您可以创建一个类 AccountRequest 扩展 FormRequest

<?php

namespace App\Http\Requests;

use App\User;
use Illuminate\Validation\Rule;
use Illuminate\Foundation\Http\FormRequest;

class AccountRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return auth()->check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => ['required', 'min:3'],
            'email' => [auth()->id() == 1 ? 'sometimes' : 'required', 'email', Rule::unique((new User)->getTable())->ignore(auth()->id())]
        ];
    }
}

然后,在您的 AccountController 中

namespace App\Http\Controllers;

use Gate;
use App\User;
use Illuminate\Support\Facades\Hash;
use App\Http\Requests\AccountRequest;

class AccountControllerextends Controller
{
    /**
     * Show the form for editing the account.
     *
     * @return \Illuminate\View\View
     */
    public function edit()
    {
        return view('account.edit');
    }

    /**
     * Update the account
     *
     * @param  \App\Http\Requests\AccountRequest  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(AccountRequest  $request)
    {

        auth()->user()->update(['name' => $request->get('name'),
                                'email' => $request->get('email')]);

        return back()->withStatus(__('Account successfully updated.'));
    }
}

你的路线看起来像这样

Route::get('account', ['as' => 'account.edit', 'uses' => 'AccountController@edit']);
Route::put('account', ['as' => 'account.update', 'uses' => 'AccountController@update']);

答案 6 :(得分:0)

'email' => "required|email|unique:users,email,$id",

laravel 8 style。我也找了很久。这种方式工作

答案 7 :(得分:-1)

if($request->ID){
            $this->validate($request, [
                'name'      => 'required',
                'mobile'    => 'required|unique:schools,mobile,'.$request->ID,
                'email'     => 'required|unique:schools,email,'.$request->ID,
                'address'   => 'required',
            ]);
        }
        else{
            $this->validate($request, [
                'name'      => 'required',
                'mobile'    => 'required|unique:schools',
                'email'     => 'required|unique:schools',
                'address'   => 'required',
            ]);
        }