简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM