Laravel validations: opposite of exists (value should not exist in the given table,column)

Issue

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?

Solution

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

Answered By – Mahdi Younesi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published