Laravel unique validation on multiple columns

前端 未结 8 1622
天涯浪人
天涯浪人 2020-11-27 05:01

I have 2 columns in table servers.

I have columns ip and hostname.

I have validation:

\'data.ip\' => [\'required         


        
相关标签:
8条回答
  • 2020-11-27 05:07

    Table

    server

    Field

    • id primary key

    • ip should be unique with hostname

    • hostname should be unique with ip

    Here I validate for Ip and the hostname should be unique.

    use Illuminate\Validation\Rule;
    
    $ip = '192.168.0.1';
    $host = 'localhost';
    

    While Create

    Validator::make($data, [
        'ip' => [
            'required',
             Rule::unique('server')->where(function ($query) use($ip,$host) {
               return $query->where('ip', $ip)->where('hostname', $host);
             });
        ],
    ]);
    

    While Update

    Add ignore after RULE

    Validator::make($data, [
        'ip' => [
            'required',
             Rule::unique('server')->where(function ($query) use($ip,$host) {
               return $query->where('ip', $ip)->where('hostname', $host);
             })->ignore($serverid);
        ],
    ]);
    
    0 讨论(0)
  • 2020-11-27 05:07

    Try this rule:
    'data.ip' => 'required|unique:servers,ip,'.$this>id.'|unique:servers,hostname,'.$this->id

    0 讨论(0)
  • 2020-11-27 05:07
    public function store(Request $request)
        {
             $this->validate($request, [
                'first_name' => 'required|regex:/^[\pL\s\-]+$/u|max:255|unique:contacts,first_name, NULL,id,first_name,'.$request->input('last_name','id'),
                'last_name'=>'required|regex:/^[\pL\s\-]+$/u|max:255|unique:contacts,last_name',
                'email' => 'required|email|max:255|unique:contacts,email',
                'job_title'=>'required',
                'city'=>'required',
                'country'=>'required'],
                [
                 'first_name.regex'=>'Use Alphabets Only',
                 'email.unique'=>'Email is Already Taken.Use Another Email',
                 'last_name.unique'=>'Contact Already Exist!. Try Again.',
                ]
            );
    
    0 讨论(0)
  • 2020-11-27 05:10

    This works for me for both create and update.

    [
         'column_1' => 'required|unique:TableName,column_1,' . $this->id . ',id,colum_2,' . $this->column_2
    ]
    

    Note: tested in Laravel 6.

    0 讨论(0)
  • 2020-11-27 05:12

    You can use Rule::unique to achieve your validation rule

    $messages = [
        'data.ip.unique' => 'Given ip and hostname are not unique',
    ];
    
    Validator::make($data, [
        'data.ip' => [
            'required',
            Rule::unique('servers')->where(function ($query) use($ip,$hostname) {
                return $query->where('ip', $ip)
                ->where('hostname', $hostname);
            }),
        ],
    ],
    $messages
    );
    

    edit: Fixed message assignation

    0 讨论(0)
  • 2020-11-27 05:14

    This is the demo code. It would help you much better. I tried covering both insert and update scenarios.

    Inside app/Http/Providers/AppServiceProvider.php

    Validator::extend('uniqueOfMultiple', function ($attribute, $value, $parameters, $validator)
        {
            $whereData = [
                [$attribute, $value]
            ];
    
            foreach ($parameters as $key => $parameter) {
    
                //At 0th index, we have table name
                if(!$key) continue;
    
                $arr = explode('-', $parameter);
    
                if($arr[0] == 'except') {
                    $column = $arr[1];
                    $data = $arr[2];
    
                    $whereData[] = [$column, '<>', $data];
                } else {
                    $column = $arr[0];
                    $data = $arr[1];
    
                    $whereData[] = [$column, $data];
                }
            }
    
            $count = DB::table($parameters[0])->where($whereData)->count();
            return $count === 0;
        });
    

    Inside app/Http/Requests/Something/StoreSometing.php

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required|max:225|uniqueOfMultiple:menus,location_id-' . $this->get('location_id', 'NULL') . ',language_id-' . $this->get('language_id', 1),
            'location_id' => 'required|exists:menu_location,id',
            'order' => 'digits_between:0,10'
        ];
    }
    

    Inside app/Http/Requests/Something/UpdateSomething.php

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required|max:225|uniqueOfMultiple:menus,location_id-' . $this->get('location_id', 'NULL') . ',language_id-' . $this->get('language_id', 'NULL') . ',except-id-' . $this->route('id', 'NULL'),
            'location_id' => 'required|exists:menu_location,id',
            'order' => 'digits_between:0,10'
        ];
    }
    

    Inside resources/lang/en/validation.php

    'unique_of_multiple' => 'The :attribute has already been taken under it\'s parent.',
    

    Here in this code, the custom validation used is uniqueOfMultiple. The first argument passed is the table_name i.e menus and all other arguments are column_name and are comma-separated. The columns are used here, name (primary column), location_id, language_id and one except-for column for the update case, except-id. The value passed for all three is - separated.

    0 讨论(0)
提交回复
热议问题