Reputation: 331
My current dilemma is this:
I have a form that I submit that indicates which rows I would like to delete from a database table. We'll call this table1.
However, this row should not be allowed to be deleted if the row's id is located in another table (there is a foreign key constraint). We'll call this table2.
Or, in other words, delete from table1 if the row's id isn't being referenced in table2.
In PHP, this would be simple for me to figure out. And honestly, I could just hard code it in PHP inside of the controller but I want to use Laravel's validation errors because currently all of the other functionality uses said error handling. The php equivalent I want to check is like this:
foreach($result->id as $id){
if (DB::table('table2')->where('fk_column', $id)->count() == 0){
DB::table('table1')->where('id', $id)->delete();
}
}
I'm not seeing my problem answered anywhere that has a sufficient explanation of how the code works. Is there a way to create a validation rule that does specifically this and spits out an error? Is there a way to just run the PHP code and throw an error that can be put into the errors array?
Upvotes: 2
Views: 2582
Reputation: 4753
The easiest solution would be to make a custom validator.
In Laravel 5.4 you could probably also get the same effect by using exists
validation rule with a custom query, as explained in the last example here https://laravel.com/docs/5.4/validation#rule-exists
That example is using Rule::exists('staff')->where(function ($query) ...
, but API documentation lists that there's also whereNot() method available https://laravel.com/api/5.4/Illuminate/Validation/Rules/Exists.html#method_whereNot
So, I guess (be warned, I haven't tested it) you'd write it something like this:
Validator::make($data, [
'delete_id' => [
'required',
Rule::exists('table2')->whereNot(function ($query) use ($data) {
$query->where('fk_column', $data['delete_id']);
}),
// ...
],
]);
Upvotes: 2