Laravel 10 with MySQL. I have a table parallel_approvers.
# id, user_id, parallel_user_id, location_id, created_at, updated_at
I am trying to validate the following conditions: If the combination of user_id and parallel_user_id values with location_id exists, then it shouldn't allow any entry with the same user_id. In other words, I want to validate the scenario like this: If a user has a parallel user and its location_id is null, it will be applied for all users. Also, if all locations are defined, then there is no need to create a specific location.
$exists = \DB::table('parallel_approvers')
->where('user_id', $validated['user_id'])
->where('parallel_user_id', $validated['parallel_user_id'])
->whereNull('location_id')->exists();
if ($exists) {
$request->validate([
'user_id' => [
'required',
Rule::unique('parallel_approvers')
->where(function ($query) use ($validated) {
$query->where('user_id', $validated['user_id'])
->where(function ($query) {
$query->whereNotNull('location_id')
->orWhereNull('location_id')
->orWhereNotNull('parallel_user_id')
->orWhereNull('parallel_user_id');
});
}),
],
]);
$parallelApprover = new ParallelApprover;
if (!auth()->user()->hasRole('admin')) {
$parallelApprover->user_id = auth()->user()->id;
} else {
$parallelApprover->user_id = $validated['user_id'];
}
$parallelApprover->parallel_user_id = $validated['parallel_user_id'];
$parallelApprover->location_id = $validated['location_id'];
$parallelApprover->created_at = now();
$parallelApprover->updated_at = now();
$parallelApprover->save();
return Helper::sendResponse($parallelApprover, 'Success', 201);
}