One possible solution to filter the error bag messages for a specific record is to include the record's ID in the error bag name itself. This can be achieved by appending the record's ID to the error bag name when displaying the errors in the modal.
Here's an example of how you can implement this solution using Laravel and Blade:
- In your controller, when returning the view that contains the modal, pass the record's ID to the view:
public function edit($id)
{
$record = Record::find($id);
return view('edit', compact('record'));
}
- In your Blade view, when rendering the modal, include the record's ID in the error bag name:
<!-- Modal -->
<div id="editModal{{ $record->id }}" x-data="{ open: false }">
<!-- Modal content -->
<div x-show="open">
<!-- Display errors for the specific record -->
@if ($errors->has('record_' . $record->id))
<ul>
@foreach ($errors->get('record_' . $record->id) as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
@endif
<!-- Form content -->
<form action="{{ route('record.update', $record->id) }}" method="POST">
<!-- Form fields -->
<!-- Submit button -->
</form>
</div>
</div>
- In your FormRequest class, when validating the form, include the record's ID in the error bag name:
public function rules()
{
return [
// Validation rules
];
}
public function attributes()
{
return [
// Attribute names
];
}
public function messages()
{
return [
// Custom error messages
];
}
protected function failedValidation(Validator $validator)
{
$validator->after(function ($validator) {
$validator->errors()->add('record_' . $this->route('record'), 'Validation failed.');
});
parent::failedValidation($validator);
}
- Finally, in your JavaScript code, you can open the modal for a specific record by setting the
openproperty totrue:
// Open the modal for a specific record
function openModal(recordId) {
document.getElementById('editModal' + recordId).__x.$data.open = true;
}
With this solution, each modal will have its own error bag scoped to the specific record. When displaying the errors, you can check if the error bag contains errors for the current record and display them accordingly.