Skip to content

A free open source IT asset/license management system

adds validation for department names at Company locations

Godfrey M92ae27129213
diff --git a/app/Models/Department.php b/app/Models/Department.php
index 7be99d097b..74e2b23df9 100644
--- a/app/Models/Department.php
+++ b/app/Models/Department.php
@@ -29,7 +29,7 @@ class Department extends SnipeModel
];
protected $rules = [
- 'name' => 'required|max:255',
+ 'name' => 'required|max:255|is_unique_department',
'location_id' => 'numeric|nullable',
'company_id' => 'numeric|nullable',
'manager_id' => 'numeric|nullable',
diff --git a/app/Providers/ValidationServiceProvider.php b/app/Providers/ValidationServiceProvider.php
index 0f6c78ee67..1f11303cab 100644
--- a/app/Providers/ValidationServiceProvider.php
+++ b/app/Providers/ValidationServiceProvider.php
@@ -2,8 +2,10 @@
namespace App\Providers;
+use App\Models\Department;
use DB;
use Illuminate\Support\ServiceProvider;
+use Illuminate\Validation\Rule;
use Validator;
/**
@@ -213,6 +215,23 @@ class ValidationServiceProvider extends ServiceProvider
return true;
}
});
+
+ Validator::extend('is_unique_department', function ($attribute, $value, $parameters, $validator) {
+ $data = $validator->getData();
+ if ($data['location_id'] != null && $data['company_id'] != null) {
+ $count = Department::where('name', $data['name'])
+ ->where('location_id', $data['location_id'])
+ ->where('company_id', $data['company_id'])
+ ->whereNotNull('company_id')
+ ->whereNotNull('location_id')
+ ->count('name');
+
+ return $count < 1;
+ }
+ else {
+ return true;
+ }
+ });
}
/**
diff --git a/resources/lang/en/admin/departments/message.php b/resources/lang/en/admin/departments/message.php
index d65f4fbb2b..2e371348b9 100644
--- a/resources/lang/en/admin/departments/message.php
+++ b/resources/lang/en/admin/departments/message.php
@@ -3,6 +3,7 @@
return array(
'does_not_exist' => 'Department does not exist.',
+ 'department_already_exists' => 'A department already exists with that name at this company location. Or choose a more specific name for this department. ',
'assoc_users' => 'This department is currently associated with at least one user and cannot be deleted. Please update your users to no longer reference this department and try again. ',
'create' => array(
'error' => 'Department was not created, please try again.',
diff --git a/resources/lang/en/validation.php b/resources/lang/en/validation.php
index e7a87aed07..367df4db45 100644
--- a/resources/lang/en/validation.php
+++ b/resources/lang/en/validation.php
@@ -49,6 +49,7 @@ return [
'ip' => 'The :attribute must be a valid IP address.',
'ipv4' => 'The :attribute must be a valid IPv4 address.',
'ipv6' => 'The :attribute must be a valid IPv6 address.',
+ 'is_unique_department' => 'The :attribute must be unique to this Company Location',
'json' => 'The :attribute must be a valid JSON string.',
'max' => [
'numeric' => 'The :attribute may not be greater than :max.',