After creating products, the next step in Laravel with Vue js CRUD is fetching product values from the database and displaying them in Vue.js 3.
This tutorial demonstrates how to get product data using a Laravel REST API and consume it in Vue.js 3 using Axios.
use App\Models\Product;
public function index()
{
$products = Product::latest()->get();
return response()->json([
'status' => true,
'data' => $products
], 200);
}
Route::get('/products', [ProductController::class, 'index']);
// src/services/api.js
import axios from 'axios'
export default axios.create({
baseURL: 'http://localhost:8000/api',
headers: {
Accept: 'application/json'
}
})
<!-- src/views/ProductList.vue -->
<template>
<div class="p-6">
<h2 class="text-xl font-bold mb-4">Product List</h2>
<table class="w-full border">
<thead>
<tr class="bg-gray-100">
<th>Name</th>
<th>SKU</th>
<th>Price</th>
<th>Stock</th>
</tr>
</thead>
<tbody>
<tr v-for="product in products" :key="product.id">
<td>{{ product.name }}</td>
<td>{{ product.sku }}</td>
<td>{{ product.price }}</td>
<td>{{ product.stock }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import api from '@/services/api'
const products = ref([])
const fetchProducts = async () => {
const response = await api.get('/products')
products.value = response.data.data
}
onMounted(fetchProducts)
</script>