I have a Laravel application with a modal box on a view page that allows users to add data to the database. By default, when the user clicks the submit button and an error is returned from the backend, the modal box disappears. I want to keep the modal box visible when errors occur. How can I achieve this?
Button to trigger Modal Box
<div><button class="add" data-modal-target="#modal-box">Add New Year</button></div>
My Modal Box
<div class="modal-box" id="modal-box">
<div class="modal-header">
<div class="title"><h1>Create School Year</h1></div>
<div data-close-button class="modal-close-btn">
<span class="material-symbols-sharp">close</span>
</div>
</div>
<hr>
<div class="modal-body">
<form action="{{ route('create.year') }}" method="post">
@csrf
<div class="input-form">
<div class="form-group">
<h3>School Year <span class="danger">*</span></h3>
<input type="text" name="name" id="name">
@error('name')
<p class="error danger">{{ $message }}</p>
@enderror
</div>
<div>
<button type="submit" class="create">Create Year</button>
</div>
</div>
</form>
</div>
</div>
JavaScript to Toggle Modal Box
const openModalButtons = document.querySelectorAll("[data-modal-target]");
const closeModalButtons = document.querySelectorAll("[data-close-button]");
const overlay = document.getElementById("overlay");
openModalButtons.forEach((button) => {
button.addEventListener("click", () => {
const modal = document.querySelector(button.dataset.modalTarget);
openModal(modal);
});
});
closeModalButtons.forEach((button) => {
button.addEventListener("click", () => {
const modal = button.closest(".modal-box");
closeModal(modal);
});
});
overlay.addEventListener("click", () => {
const modals = document.querySelectorAll(".modal-box.active");
modals.forEach((modal) => {
closeModal(modal);
});
});
function openModal(modal) {
if (modal == null) return;
modal.classList.add("active");
overlay.classList.add("active");
}
function closeModal(modal) {
if (modal == null) return;
modal.classList.remove("active");
overlay.classList.remove("active");
}
My Controller
public function CreateYear(Request $request)
{
$validateData = $request->validate([
'name' => 'required|unique:academic_years,name'
]);
$data = new AcademicYear();
$data->name = $request->name;
$data->save();
$notification = array(
'message' => 'Academic Year Created Successfully!',
'alert-type' => 'success'
);
return redirect()->route('view.year')->with($notification);
}
In your form you can add a hidden input with id of it's modal. On submit in your controller you get the id and send it back with return in form of variable. And when returning to view you check if this variable exists, and if yes, you call the corresponding modal open :
<input type="hidden" name="activeModal" value="modal-box">
And somewhere in your view you add :
@isset($activeModal)
<script>
let modal = document.querySelector({{ $activeModal }});
openModal(modal);
</script>
@endisset