Reputation: 933
I have table employee
that has a nullable column substitute
referencing to another employee. The API I'm developing can receive a DELETE request for /employee/{employee_id}
and it should validate employee_id to make sure it is not referenced by any other row. So basically, I need a validation rule like this:
Validator::make($data, [
'employee_id' => '!exists:employee,substitute'
], [
'!exists' => 'Employee :employee_id cannot be deleted as it is being used as substitute for other employees' // custom message
])
Does Laravel have something similar out of the box or should I define custom validation rule?
Upvotes: 4
Views: 3217
Reputation: 19573
If the list of existing ids is not very big, you could do this
use Illuminate\Validation\Rule;
//...
Validator::make($data, [
'employee_id' => Rule::notIn(Employee::pluck('substitute'))
], [
'eomployee_id.not_in' => 'Employee :employee_id cannot be deleted as it is being used as substitute for other employees' // custom message
])
Upvotes: 0
Reputation: 7489
Either use unique
rule or create a new rule
'employee_id' => 'unique:employee,substitute'
Or
Validator::extend('not_exists', function($attribute, $value, $parameters, $validator) {
$exists = DB::table($parameters[0])
->where($parameters[1], '=', $value)
->exists();
return $exists === false;
});
Upvotes: 3