Livewire pagination returning 404 not found after deleting a record

Viewed 806

After calling the delete() method, when trying to go to another page of the table, I get an 404 not found error.

This is my delete method:

public $selected = [];

 public function deleteSelected()
    {
        $products = Products::whereKey($this->selected);
        $products->delete();
        $this->showDeleteModal = false;
        $this->selected = [];
    }

I tried the following

  • To change the way I call the pagination inside the component's view so instead of {{ $products->links() }} I tried {{ $products->withQueryString()->links() }}
  • I tried to change the 'asset_url' from null to http://localhost in config\livewire.php
  • I tried php artisan route:clear and php artisan route:cache

None of the above seem to fix the problem so I ended up here hoping that some of you encountered the same problem and managed to solve it.

Thanks.

/** UPDATE **/

I just rebuilt the datatable on a fresh Laravel project and I have the same error.

I made a github repo with the code if anyone interested: https://github.com/mvpopuk/livewire-datatable

2 Answers

It seems you are watching livewire screencasts, which I also have been doing. And most probably you are deleting the record right after creating it. In that case, "editing" attribute in your Livewire component still remains indicating an already deleted model which causes 404 response for each next requests.

You should reset "editing" attribute to a new model after delete operations.

public function deleteSelected()
{
    $products = Products::whereKey($this->selected);
    $products->delete();
    $this->showDeleteModal = false;
    $this->selected = [];
    $this->editing = Products:make(); // or new Product()
}

Interestingly, Caleb Porzio missed that point as well and his demo project has this little bug.

I have faced the same issue when deleting a user record (in a modal) that was created just then.

Then I have edited the record, using user data like:

$user = User::findOrFail($id);
$this->user = $user; // assigning the public property for edit modal (in Livewire memory now)

And then when immediately trying to delete it, I got the 404 issue. To solve this issue, I have used the solution from this link: Basically I had to set the corresponding Model record to null, that still exists in Livewire memory (during Edit in last step).

$user_id = User::findOrFail($id);
$user_id->delete();
$this->user = null; // Important

To solve this issue in another way, we can also opt for soft delete.. by just updating the user record status column to 0 in database, so that the model record exists in Livewire memory.

Related