I’m working with Laravel v11 and wanted to show a Modal on users list blade when clicking on Add New Button:
<div class="card-header">
<div class="card-tools">
<button type="button" wire:click="addNew">Add New</button>
</div>
</div>
And this is AppLivewireAdminUsersListUsers Class:
class ListUsers extends Component
{
public $users;
public $name;
public $email;
public function mount()
{
// Fetching users from the database
$this->users = User::all();
}
public function addNew()
{
// Trigger modal open event
$this->dispatch('showModal');
}
public function save()
{
// Save logic
User::create([
'name' => $this->name,
'email' => $this->email,
]);
// Reset input fields
$this->reset('name', 'email');
// Close the modal after saving
$this->dispatch('closeModal');
}
public function render()
{
return view('livewire.admin.users.list-users')->layout('layouts.app');
}
}
But now when clicking on Modal, I get this at Console Bar and nothing appears as Modal:
So what’s going wrong here? How can I show the Modal properly in this case?
Note that I’m using “livewire/livewire”: “^3.5”
And here is the script in `list-users` blade:
<script>
document.addEventListener('livewire:load', function () {
Livewire.on('showModal', () => {
const modal = document.getElementById('myModal');
if (modal) {
modal.style.display = 'block'; // Show the modal
}
});
// Close modal when the close button is clicked
document.addEventListener('click', function (event) {
const modal = document.getElementById('myModal');
if (event.target.classList.contains('close')) {
modal.style.display = 'none'; // Hide the modal
}
});
});
</script>