由于this link和this 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.
那会发生什么,我该如何解决这个问题?
答案 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),
],
]);