Search code examples
phplaravellaravel-livewire

Livewire pagination returning 404 not found after deleting a record


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


Solution

  • 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.