首页 > 解决方案 > 如果laravel validate中的外键相同,如何使名称唯一

问题描述

我有两张桌子“房间”和“床”,当 room_id 相同时,我想唯一的床名。我应该怎么办。

public function store(Request $request)
    {
        $roomid =  $request->input('room_id');

        //
        $attributes = request()->validate([

            'room_id' => ['required', 'integer', 'min:1'],
            'name' => ['required', 'string', 'min:1', 'max:10', 'unique:App\Models\bed,name,room_id' . $roomid],
            'type' => ['nullable', 'string', 'min:1', 'max:10'],
            'description' => ['nullable', 'string', 'min:1', 'max:20']


        ]);
        bed::create($attributes);
}
~~~

标签: phplaravel

解决方案


您应该使用闭包而不是规则对象,因为在整个应用程序中似乎不需要此验证,您只需要在这里。

将您的验证更改为:

        $attributes = request()->validate([

            'room_id' => ['required', 'integer', 'min:1'],
            'name' => [
                'required', 'string', 'min:1','max:10',
                function ($attribute, $value, $fail) {
                    
                    // Checke if name is unique in that room
                    $name_exists = \App\Models\Bed::where('name', $value)->where('room_id', request()->input('room_id'))->count() > 0;

                    if ($name_exists) {
                        $fail('The '.$attribute.' must be unique in this room.');
                    }
                }
            ],
            'type' => ['nullable', 'string', 'min:1', 'max:10'],
            'description' => ['nullable', 'string', 'min:1', 'max:20']
        ]);

资源


推荐阅读