Added a validation to use the same name in categories with different types

This commit is contained in:
Ivan Nieto Vivanco 2021-10-08 15:19:16 -05:00
parent 5f52ee59b2
commit 23b770fac6
3 changed files with 43 additions and 3 deletions

View file

@ -0,0 +1,25 @@
<?php
namespace App\Http\Traits;
trait TwoColumnUniqueUndeletedTrait
{
/**
* Prepare a unique_ids rule, adding a model identifier if required.
*
* @param array $parameters
* @param string $field
* @return string
*/
protected function prepareTwoColumnUniqueUndeletedRule($parameters, $field)
{
$column = $parameters[0];
$value = $this->{$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;
}
}

View file

@ -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.

View file

@ -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: