skip to Main Content

I really hope someone can help me

So I have a SPA Laravel project and have a page of products with a delete button, which works fine, the following code is what I use inside the "Index.vue"

import { ref } from 'vue';
import { Inertia } from '@inertiajs/inertia';
import { Head, Link } from '@inertiajs/vue3';
import ConfirmationModal from '@/Components/ConfirmationModal.vue';
    
export default {
  components: {
    ConfirmationModal,
    Link
  },
  props: {
    products: Array,
    flash: Object,
  },
  setup(props) {
    const showModal = ref(false);
    const productIdToDelete = ref(null);
    const products = ref(props.products); // Add this line

    const showDeleteConfirmation = (id) => {
      productIdToDelete.value = id;
      showModal.value = true;
    };
    
    const confirmDelete = () => {
      if (productIdToDelete.value) {
        Inertia.delete(`/products/${productIdToDelete.value}`, {
          preserveScroll: true,
          onFinish: () => {
            closeModal();
            // Remove the deleted product from the products array
            const index = products.value.findIndex(product => product.id === productIdToDelete.value);
            if (index !== -1) {
              products.value.splice(index, 1);
            }
          },
        });
      }
    };
    
    const closeModal = () => {
      showModal.value = false;
    };
    
    return {
      showModal,
      showDeleteConfirmation,
      confirmDelete,
      closeModal,
      products, // Make sure to return products here
    };
  },
};

and inside my ProductController.php I have

public function destroy(Product $product)
{
    $product->delete();

    return response(['id' => $product->id], Response::HTTP_OK);
}

Which is great and when I delete a item it removes it from the list and retains the SPA

The problem is, when it does so, it displays a modal with (for example)

{"id":92}

which I understand given I pass

return response(['id' => $product->id], Response::HTTP_OK);

But I dont want to display a modal, and if I remove that line, it reloads the page following the delete and kills the SPA

I’ve tired lots of different options, but cannot seem to find how to sort this

Any suggestions?

Thanks

2

Answers


  1. You’re returning a normal HTTP response, but you need to return an Inertia response.

    The quick fix is to add this to your controller.

    return to_route('your_route_name');
    

    More details can be found here in the Inertia documentation

    Login or Signup to reply.
  2. Use this:

    return back();
    

    This should return to the page without reloading it. If you want to send along data you can do it like this:

    return back()->with([
     'message' => 'Product ' .
      $product->name . ' has been. 
      updated.']);
    

    The message should be found in the usePage().props.message

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search