From 5201cdb0e305760d5ac6106c33f50c0149c5f6de Mon Sep 17 00:00:00 2001 From: Daeng Deni Mardaeni Date: Fri, 1 Nov 2024 09:39:41 +0700 Subject: [PATCH] Drop unique constraint on 'cif' in debitures table Remove the unique constraint on the 'cif' field in the debitures table and refactor the `UniqueCifExceptZero` validation rule to handle the uniqueness check more robustly. Also, add an unused import statement for `UniqueExcept` in `DebitureRequest`. --- app/Http/Requests/DebitureRequest.php | 1 + app/Rules/UniqueCifExceptZero.php | 41 +++++++++++-------- ...24_11_01_023117_update_debitures_table.php | 28 +++++++++++++ 3 files changed, 53 insertions(+), 17 deletions(-) create mode 100644 database/migrations/2024_11_01_023117_update_debitures_table.php diff --git a/app/Http/Requests/DebitureRequest.php b/app/Http/Requests/DebitureRequest.php index 7f83fbb..40b608e 100644 --- a/app/Http/Requests/DebitureRequest.php +++ b/app/Http/Requests/DebitureRequest.php @@ -4,6 +4,7 @@ use Illuminate\Foundation\Http\FormRequest; use Modules\Lpj\Rules\UniqueCifExceptZero; + use Modules\Lpj\Rules\UniqueExcept; class DebitureRequest extends FormRequest { diff --git a/app/Rules/UniqueCifExceptZero.php b/app/Rules/UniqueCifExceptZero.php index c8173d1..03accd3 100644 --- a/app/Rules/UniqueCifExceptZero.php +++ b/app/Rules/UniqueCifExceptZero.php @@ -1,25 +1,32 @@ id = $id; - } + protected $id; - public function validate($attribute, $value, $fail): void - { - if (Debiture::where($attribute, $value) - ->where('id', '!=', $this->id) - ->where($attribute, '!=', '0000000000') - ->exists()) { - $fail('The :attribute field must be uniquse.'.$this->id); + public function __construct($id = null) + { + $this->id = $id; + } + + /** + * Run the validation rule. + */ + public function validate(string $attribute, mixed $value, Closure $fail) + : void { + if ($value !== '0000000000' && $value !== null && Debiture::query()->where($attribute, $value)->when( + $this->id, + function ($query) { + $query->where('id', '!=', $this->id); + }, + )->exists()) { + $fail('The :attribute field must be unique.'); + } } } -} diff --git a/database/migrations/2024_11_01_023117_update_debitures_table.php b/database/migrations/2024_11_01_023117_update_debitures_table.php new file mode 100644 index 0000000..cadf6b0 --- /dev/null +++ b/database/migrations/2024_11_01_023117_update_debitures_table.php @@ -0,0 +1,28 @@ +dropUnique(['cif']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('debitures', function (Blueprint $table) { + $table->string('cif')->unique()->change(); + }); + } +};