Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

froemic's avatar

Validating Destroy Request

I have a DB Model with Students and Classes. Several students belong to one class.

If the user wants to delete a class with students assigned to it, this request SHOULD fail. However, it does fail with an SQL Integrity Constraint violation, because I could not figure out how to test for this case with Laravel's validator. Any ideas?

0 likes
2 replies
Demers94's avatar
Demers94
Best Answer
Level 13

You could add your check just after the basic validation and before you actually delete the record :

if($class->students->count()){
  // Error, can't a class with students
}  

 // Later ...
 $class->delete();

You could also define a custom validation rule : https://laravel.com/docs/5.4/validation#custom-validation-rules

I've never used them so I'm not sure what the actual rule would look like though.

1 like

Please or to participate in this conversation.