The issue you're experiencing is related to how Livewire handles data binding and component reactivity. When you delete a user, the $users property in your parent component (Show) is not automatically updated unless you explicitly refresh it, which is why your table appears empty after a delete operation if you don't re-query the users.
Here's a breakdown of why this happens and how you can address it:
Why the Data is Lost
-
Data Binding: In Livewire, properties are not automatically reactive in the sense that they don't automatically update when the underlying data changes in the database. When you delete a user, the
$usersproperty still holds the old data unless you refresh it. -
Component Lifecycle: The
mountmethod is only called once when the component is initialized. It doesn't get called again unless the component is re-rendered from scratch, which doesn't happen in your case when you delete a user.
Solution
To ensure that your table reflects the current state of the database after a user is deleted, you need to refresh the $users property. You are already doing this by re-querying the users in the deleteUser method:
public function deleteUser($id)
{
$user = User::findOrFail($id);
$user->delete();
$this->users = User::all(); // Refresh the users list
Flux::modal('delete-user')->close();
$this->dispatch('alert', ['title' => 'L\'utilisateur a bien été supprimé', 'type' => 'success']);
}
This line is necessary to update the $users property with the current list of users from the database. Without it, the $users property would still contain the deleted user, leading to an inconsistency between your database and the displayed data.
Alternative Approach
If you want to avoid re-querying the database, you could manually remove the user from the $users array after deletion:
public function deleteUser($id)
{
$user = User::findOrFail($id);
$user->delete();
// Remove the user from the local $users array
$this->users = $this->users->filter(function ($user) use ($id) {
return $user->id !== $id;
});
Flux::modal('delete-user')->close();
$this->dispatch('alert', ['title' => 'L\'utilisateur a bien été supprimé', 'type' => 'success']);
}
This approach avoids the need to re-query the database, but it requires that the $users property is a collection or array that you can manipulate.
Conclusion
The key takeaway is that Livewire doesn't automatically sync your component's properties with the database. You need to manage this synchronization manually, either by re-querying the database or by updating the properties directly in your component logic.