From 4dc412e53c5097e3aea4529b20311d2902527383 Mon Sep 17 00:00:00 2001 From: Miguel Nogueira Date: Sun, 12 Jul 2020 06:39:39 +0100 Subject: [PATCH] Added check for constrained models when deleting --- app/Form.php | 2 +- app/Http/Controllers/FormController.php | 20 ++++++++++++++------ 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/app/Form.php b/app/Form.php index 9789cdc..dc64af2 100644 --- a/app/Form.php +++ b/app/Form.php @@ -16,7 +16,7 @@ class Form extends Model public function vacancies() { - return $this->hasMany('vacancies', 'vacancyFormID', 'id'); + return $this->hasMany('App\Vacancy', 'vacancyFormID', 'id'); } public function responses() diff --git a/app/Http/Controllers/FormController.php b/app/Http/Controllers/FormController.php index 6d63742..bc95730 100644 --- a/app/Http/Controllers/FormController.php +++ b/app/Http/Controllers/FormController.php @@ -80,17 +80,25 @@ class FormController extends Controller $form = Form::find($id); $this->authorize('delete', $form); + $deletable = true; - // TODO: Check if form is linked to vacancies before allowing deletion - if (!is_null($form)) + + if (!is_null($form) && !is_null($form->vacancies) && $form->vacancies->count() !== 0 || !is_null($form->responses)) { - $form->delete(); + $deletable = false; + } + + if ($deletable) + { + $form->delete(); - $request->session()->flash('success', 'Form deleted successfully.'); - return redirect()->back(); + $request->session()->flash('success', 'Form deleted successfully.'); + } + else + { + $request->session()->flash('error', 'You cannot delete this form because it\'s tied to one or more applications and ranks, or because it doesn\'t exist.'); } - $request->session()->flash('error', 'The form you\'re trying to delete does not exist.'); return redirect()->back(); }