add validation for enabled labels, rename enable (to enabled) in labels table, and update the enabled attribute of corresponding labels to false when cycle saved

This commit is contained in:
Moradi
2025-03-13 12:45:00 +03:30
parent 034000bcef
commit 1d98af0113
6 changed files with 82 additions and 5 deletions
+17
View File
@@ -0,0 +1,17 @@
<?php
if (!function_exists('pluckValues')) {
/**
* Extracts the values of a given key from an array of associative arrays.
*
* @param array $array The input array of associative arrays.
* @param string $key The key whose values need to be extracted.
* @return array An array containing the values of the specified key.
*/
function pluckValues(array $array, string $key): array
{
return array_map(function ($item) use ($key) {
return $item[$key] ?? null;
}, $array);
}
}
+3 -2
View File
@@ -3,6 +3,7 @@
namespace App\Http\Requests;
use App\Models\Cycle;
use App\Rules\ValidEnabledLabels;
use Illuminate\Foundation\Http\FormRequest;
@@ -27,8 +28,8 @@ class StoreCycleRequest extends FormRequest
'sterilizer_id' => 'required',
'cycle_number' => 'required|unique:cycles,cycle_number',
'note' => 'nullable',
'labels' => 'required|array|distinct',
'labels.*.id' => 'required|numeric|exists:labels,id',
'labels' => ['required','array','distinct',new ValidEnabledLabels()],
];
break;
}
@@ -40,8 +41,8 @@ class StoreCycleRequest extends FormRequest
'sterilizer_id' => 'required',
'cycle_number' => 'required|unique:cycles,cycle_number',
'note' => 'nullable',
'labels' => 'required|array|distinct',
'labels.*.id' => 'required|numeric|exists:labels,id',
'labels' => ['required','array','distinct',new ValidEnabledLabels()],
];
break;
+1 -2
View File
@@ -23,8 +23,7 @@ class UpdateLabelsCycleNumber
{
$cycle = $event->cycle;
$cycleNumber = $cycle->cycle_number;
// dd($cycle->labels);
$cycle->labels()->update(['cycle_number' => $cycleNumber]);
$cycle->labels()->update(['cycle_number' => $cycleNumber, 'enabled' => false]);
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace App\Rules;
use App\Models\Label;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class ValidEnabledLabels implements ValidationRule
{
/**
* Run the validation rule.
*
* @param \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$formattedVal = pluckValues($value,'id');
$validIds = Label::whereIn('id', $formattedVal)
->where('enabled', true)
->pluck('id')
->toArray();
if(count(array_diff($formattedVal, $validIds)) !== 0)
{
$fail('the :attribute must be enabled.');
}
}
}