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?
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;
});