Laravel控制器中电话号码列的唯一验证无法正常工作

jobtbby3  于 2023-05-30  发布在  其他
关注(0)|答案(2)|浏览(139)

我想将“电子邮件”列和“电话号码”列验证为“唯一”。电话号码作为呼叫代码和电话号码的连接提交到数据库。这是我的代码。

public function customRegistration(Request $request)
{
    $request->validate([
        'name' => 'required',
        'email' => 'required|email|unique:users',
        'country' => 'required',
        'phone_no' => 'required|unique:users',
        'password' => 'required',
    ]);

    $data = $request->all();
    $check = $this->create($data);

    return redirect('login')->with('message', 'Signing up successful !!!');
}

public function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'country' => $data['country'],
        'phone_no' => $data['calling_code'] . '-' . $data['phone_no'],
        'password' => Hash::make($data['password']),
    ]);
}

在上面的代码中,电子邮件验证工作完美。但是相同的电话号码可以被提交到DB。验证规则对电话号码无效。我找不到错误在哪里。我应该在哪里更改以验证电话号码是否唯一?

watbbzwu

watbbzwu1#

您可以选择创建自定义验证规则来验证电话号码的唯一性。

php artisan make:rule UniquePhoneNumber

app/Rules/UniquePhoneNumber.php

<?php
 
namespace App\Rules;
 
use Closure;
use App\Models\User;
use Illuminate\Contracts\Validation\ValidationRule;
 
class UniquePhoneNumber implements ValidationRule
{
    /**
     * Run the validation rule.
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        return User::where('phone_no', request('calling_code') . '-' . $value)
                    ->doesntExist();
    }
}

然后使用新的自定义验证规则:

use App\Rules\UniquePhoneNumber;

public function customRegistration(Request $request)
{
    $request->validate([
        'name' => 'required',
        'email' => 'required|email|unique:users',
        'country' => 'required',
        'phone_no' => ['required', new UniquePhoneNumber],
        'password' => 'required',
    ]);

    $data = $request->all();
    $check = $this->create($data);

    return redirect('login')->with('message', 'Signing up successful !!!');
}
hs1rzwqc

hs1rzwqc2#

编辑:

(感谢@brombeer,我注意到你通过连接插入值,同时将初始值与数据库中已经连接的值进行比较,这意味着你没有在数据库中强制唯一性)
所以你可以用漂亮的可接受的答案来做,或者你可以用验证来做,

'phone_number' => [
        'required',
        function ($attribute, $value, $fail) use ($request) {
            $callingCode = $request->input('calling_code');
            $phoneNumber = $callingCode. '-' . $value;
            $exists = User::where('phone_number', $phoneNumber)->exists();

            if ($exists) {
                $fail('The ' . $attribute . ' has already been taken.');
            }
        },
    ],

相关问题