Laravel & Vue.js 3 Product Delete Tutorial (API Based)

Laravel & Vue.js 3 Product Delete Tutorial (API Based)

 In this tutorial, you will learn how to delete a product using Laravel and Vue.js 3 (API based approach). This guide follows the same CRUD pattern used in product create and update tutorials and is ideal for building modern single-page applications (SPA). 

Laravel API Route for Product Delete

routes/api.php:

use App\Http\Controllers\Api\ProductController;

Route::delete('/products/{id}', [ProductController::class, 'destroy']);

Laravel ProductController Delete Method

app/Http/Controllers/Api/ProductController.php:

public function destroy($id)
{
    $product = Product::find($id);

    if (!$product) {
        return response()->json([
            'status' => false,
            'message' => 'Product not found'
        ], 404);
    }

    $product->delete();

    return response()->json([
        'status' => true,
        'message' => 'Product deleted successfully'
    ], 200);
}

Vue.js 3 Delete Product Method

<script setup>
import axios from 'axios'

const deleteProduct = async (id) => {
    if (!confirm('Are you sure you want to delete this product?')) {
        return
    }

    try {
        const response = await axios.delete(
            `http://127.0.0.1:8000/api/products/${id}`
        )

        alert(response.data.message)

        // Reload product list
        fetchProducts()

    } catch (error) {
        alert('Failed to delete product')
    }
}
</script>
<button
    class="btn btn-danger"
    @click="deleteProduct(product.id)"
>
    Delete
</button>