I want to validate sequence of items. In my idea sequence field must be exists in database sequence column or must be one plus more than maximum of present sequence. I have this code in view:
<select id="sequence" name="sequence" value="{{ old('sequence') }}">
@foreach ($items = App\Models\Item::all()->sortBy('sequence') as $item)
<option value="{{ $item->sequence }}">{{ $item->sequence }}</option>
@endforeach
<option value="{{ $items->max('sequence') 1 }}">{{ $items->max('sequence') 1 }}</option>
</select>
now I have a problem to validate request('sequence') in controller. I'm looking for some code like this
Rule::exists('items', 'sequence') OR equal => ($items->max('sequence') 1)
Note: I have a function for updating sequence when the value isn't maximum plus one.
CodePudding user response:
You can use Rule::when()
to validate.
use App\Models\Item;
$max = Item::max('sequence');
Controller
$validatedData = $request->validate([
'sequence' => ['required', 'integer', Rule::when($request->sequence != $max 1, ['exists:items,sequence'])],
]);
Or,
FormRequest
public function rules()
{
return [
'sequence' => ['required', 'integer', Rule::when($this->sequence != $max 1, ['exists:items,sequence'])],
];
}