在 Laravel 验证规则 'Exists' 中使用模型关系

Using models relationships in Laravel Validation Rule 'Exists'

数据库架构

users
 -id
 -name
 -email
 ...

roles
 -id
 -name

User may have multiple roles and vice-versa (i already defined relationships in models)

枢轴table

role_user
 -id
 -user_id
 -role_id

试图制定的验证规则:user_id 必须存在于用户 table 中并且角色 ID = 4

//...
'user_id' => ['nullable', Rule::exists('users')->where(
                function ($query) { 
                    $query->whereHas('roles', 
                        function ($q) { 
                            $q->where('id', 4); 
                        }
                    );
                }
)], 
//...

Error message : "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'has' in 'where clause' (SQL: select count(*) as aggregate from users where user_id = 0 and (has = roles))"

我会用这个。这将解决您的问题,但我不知道哪个是最好的方法。

    use Validator; // on the top

    $validator = Validator::make($request->all(), [
        'user_id' => 'nullable|numeric|exists:users,id',
    ]);
    if ($validator->fails()) {            
        return response()->json($validator->errors(), 422);
    }
    $user = User::find($request->user_id);
    if(!$user || !$user->roles->first() || $user->roles->first()->id != 4) {
        return response()->json(['user_id'=>['You dont have permission.']], 422);
    }

您可以尝试另一种方法

'user_id'  => [
            'nullable',
            'numeric',
            'exists:users,id',
            function ($attribute, $value, $fail) { 
                $editorsIDs = User::whereHas('roles', function ($q) {
                    $q->where('id', 4);
                })->pluck('id');

                if(! $editorsIDs->contains($value)) {                        
                    $fail('You dont have permission.');
                }}
            ]

我用

解决了
$usersWhereHasEditorRole = User::whereHas('roles', function ($q) {
     $q->where('id', 4);
})->pluck('id')->unique('id')->toArray();

$validator = Validator::make($request->all(), [
                'name' => 'required|alpha', // commun
                'email' => 'required|email|unique:users', // commun
                'password' => 'required|min:8|regex:/[a-z]/|regex:/[A-Z]/|regex:/[0-9]/|regex:/[@$!%*#?&]/', // commun
                'c_password' => 'required|same:password', // commun
                //...
                'user_id' => ['nullable', Rule::in($usersWhereHasEditorRole)],
                //...
]);


if ($validator->fails()) {
      return $this->sendError('Validation Error.', $validator->errors(), 400);
}

dd('passes');