Laravel unique validation on multiple columns

前端 未结 8 1620
天涯浪人
天涯浪人 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:19

    Laravel 5.6 and above

    Validation in the controller

    The primary key (in my case) is a combination of two columns (name, guard_name)

    I validate their uniqueness by using the Rule class both on create and on update method of my controller (PermissionsController)


    PermissionsController.php

    <?php
    
    namespace App\Http\Controllers;
    
    use App\Permission;
    
    use Illuminate\Http\Request;
    use Illuminate\Validation\Rule;
    use App\Http\Controllers\Controller;
    
    class PermissionsController extends Controller
    {
    
        /**
         * Store a newly created resource in storage.
         */
        public function store(Request $request)
        {
            request()->validate([
    
                'name'        => 'required|max:255',
    
                'guard_name'  => [
    
                    'required', 
    
                    Rule::unique('permissions')->where(function ($query) use ($request) {
    
                        return $query
                            ->whereName($request->name)
                            ->whereGuardName($request->guard_name);
                    }),
                ],
            ],
            [
                'guard_name.unique' => __('messages.permission.error.unique', [
    
                    'name'              => $request->name, 
                    'guard_name'        => $request->guard_name
                ]),
            ]);
    
            Permission::create($request->all());
    
            flash(__('messages.permission.flash.created'))->success();
    
            return redirect()->route('permission.index');
        }
    
    
        /**
         * Update the specified resource in storage.
         */
        public function update(Request $request, Permission $permission)
        {
            request()->validate([
    
                'name'        => 'required|max:255',
    
                'guard_name'  => [
    
                    'required', 
    
                    Rule::unique('permissions')->where(function ($query) use ($request, $permission) {
    
                        return $query
                            ->whereName($request->name)
                            ->whereGuardName($request->guard_name)
                            ->whereNotIn('id', [$permission->id]);
                    }),
                ],
            ],
            [
                'guard_name.unique' => __('messages.permission.error.unique', [
    
                    'name'              => $request->name, 
                    'guard_name'        => $request->guard_name
                ]),
            ]);
    
            $permission->update($request->all());
    
            flash(__('messages.permission.flash.updated'))->success();
    
            return redirect()->route('permission.index');
        }
    }
    

    Notice in the update method i added an additional query constraint [ whereNotIn('id', [$permission->id]) ] to ignore the current model.


    resources/lang/en/messages.php

    <?php
    
    return [
    
        'permission' => [
    
            'error' => [
                'unique' => 'The combination [":name", ":guard_name"] already exists',
            ],
    
            'flash' => [
                'updated' => '...',
                'created' => '...',
            ],
        ]
    ]
    

    The flash() method is from the laracasts/flash package.

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

    The following will work on the create

    'data.ip' => ['required', 'unique:servers,ip,'.$this->id.',NULL,id,hostname,'.$request->input('hostname')]
    

    and the following for the update

    'data.ip' => ['required', 'unique:servers,ip,'.$this->id.','.$request->input('id').',id,hostname,'.$request->input('hostname')]
    

    I'm presuming that id is your primary key in the table. Substitute it for your environment.


    The (undocumented) format for the unique rule is:

    table[,column[,ignore value[,ignore column[,where column,where value]...]]]

    Multiple "where" conditions can be specified, but only equality can be checked. A closure (as in the accepted answer) is needed for any other comparisons.

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