首页 文章

Laravel . 请求验证 . 来自少数领域的独特组合

提问于
浏览
0

我想知道如何从几列中验证独特的组合?

For example:

Table PhoneBook
Field: FirstName, LastName, PhoneNumber, Address

如果有来自伦敦的数据库John Smith那么我想给John Smith添加记录,但不能从伦敦添加记录 .

我想要从字段组合的唯一键:FirstName,LastName,Address .

请帮忙 .

2 回答

  • 1

    如果值存在,您应该首先检查数据库

    $members =
    PhoneBook::whereFirstName($firstName)->whereLastName($lastName)->whereAddress($address)->get();
    if(count($members) > 0){}   // Your Create Code with different values
    else{}   //Your Create Code with Same Values
    
  • -1

    对于Laravel 5.5

    • 运行命令 php artisan make:rule UniqueNameAddress . 这将在app / Rules文件夹中创建一个具有给定名称的类( UniqueNameAddress

    • UniqueNameAddress 类中,有一个 passes 方法 . 这是您验证所请求的名称和地址尚未被其他用户使用的位置 . 您可以在 passes 方法中粘贴和自定义下面的代码 .

    $matches = PhoneBook::whereFirstName(request(first_name))
            ->whereLastName(request(last_name))
            ->whereAddress(request(address))
            ->count();
    
    return $matches === 0;
    
    • 在同一类的 messages 方法中,设置将在出错时返回的消息 .

    • 使用自定义规则如下

    $request->validate([
        'first_name' => ['required', new UniqueNameAddress],
    ]);
    

相关问题