Laravel会在API级别上验证正在更新用户的唯一移动设备吗?

时间:2018-07-03 12:33:04

标签: php laravel laravel-5.6

由于this linkthis link不能帮助我,我想知道如何从正在API级更新它的用户中验证唯一的移动设备。例如:

public function register(Request $request)
{
    try {
        $user = User::whereMobileNumber($request->mobile_number)->first();

        /*VALIDATION IF USER NOT FOUND*/
        if ($user == null) {
            $validator = Validator::make($request->all(), [
                'mobile_number' => 'required|string|unique:users|min:11|max:11',
            ]);
        }else{
            /*VALIDATION IF USER HAVE DATA AND IGNORE CHECK MOBILE NUMBER*/
            $validator = Validator::make($request->all(), [
                'mobile_number' => 'required|string|min:11|max:11|unique:users,mobile_number,'.$user->mobile_number,
            ]);
        }

        if ($validator->fails()) {
            return response(['data' => $validator->errors()->all(), 'status' => $user->mobile_number], 200);
        }

        ...
    } catch (\Exception $ex) {
        return response(['data' => $ex->getMessage(), 'status' => '5'], 200);
    }
}

不幸的是我得到这个错误:

The mobile number has already been taken.

那会发生什么,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您必须传递用户ID而不是电话号码:

$validator = Validator::make($request->all(), [
                'mobile_number' => 'required|string|min:11|max:11|unique:users,mobile_number,'.$user->id,
            ]);

或者您可以像这样使用laravel Rule类:

use Illuminate\Validation\Rule;

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