diff --git a/app/Http/Traits/TwoColumnUniqueUndeletedTrait.php b/app/Http/Traits/TwoColumnUniqueUndeletedTrait.php new file mode 100644 index 0000000000..4aae02bfbd --- /dev/null +++ b/app/Http/Traits/TwoColumnUniqueUndeletedTrait.php @@ -0,0 +1,25 @@ +{$parameters[0]}; + + if ($this->exists) { + return 'two_column_unique_undeleted:'.$this->table.','.$this->getKey().','.$column.','.$value; + } + + return 'two_column_unique_undeleted:'.$this->table.',0,'.$column.','.$value; + } +} diff --git a/app/Models/Category.php b/app/Models/Category.php index 36cad63ec7..6445dec5cf 100755 --- a/app/Models/Category.php +++ b/app/Models/Category.php @@ -2,7 +2,7 @@ namespace App\Models; -use App\Http\Traits\UniqueUndeletedTrait; +use App\Http\Traits\TwoColumnUniqueUndeletedTrait; use App\Models\Traits\Searchable; use App\Presenters\Presentable; use Illuminate\Database\Eloquent\Factories\HasFactory; @@ -38,7 +38,7 @@ class Category extends SnipeModel */ public $rules = [ 'user_id' => 'numeric|nullable', - 'name' => 'required|min:1|max:255|unique_undeleted', + 'name' => 'required|min:1|max:255|two_column_unique_undeleted:category_type', 'require_acceptance' => 'boolean', 'use_default_eula' => 'boolean', 'category_type' => 'required|in:asset,accessory,consumable,component,license', @@ -53,7 +53,8 @@ class Category extends SnipeModel */ protected $injectUniqueIdentifier = true; use ValidatingTrait; - use UniqueUndeletedTrait; + use TwoColumnUniqueUndeletedTrait; + /** * The attributes that are mass assignable. diff --git a/app/Providers/ValidationServiceProvider.php b/app/Providers/ValidationServiceProvider.php index d68c79a268..0f6c78ee67 100644 --- a/app/Providers/ValidationServiceProvider.php +++ b/app/Providers/ValidationServiceProvider.php @@ -54,6 +54,20 @@ class ValidationServiceProvider extends ServiceProvider } }); + // Unique if undeleted for two columns + // Same as unique_undeleted but taking the combination of two columns as unique constrain. + Validator::extend('two_column_unique_undeleted', function ($attribute, $value, $parameters, $validator) { + if (count($parameters)) { + $count = DB::table($parameters[0]) + ->select('id')->where($attribute, '=', $value) + ->whereNull('deleted_at') + ->where('id', '!=', $parameters[1]) + ->where($parameters[2], $parameters[3])->count(); + + return $count < 1; + } + }); + // Prevent circular references // // Example usage in Location model where parent_id references another Location: