Building a Laravel and Vue.js CRUD Application: Step-by-Step Guide


Building a CRUD (Create, Read, Update, Delete) application using Laravel and Vue.js involves integrating Laravel as the backend and Vue.js as the frontend. Here’s a guide to building a CRUD system:


1. Setting Up the Environment

Step 1: Install Laravel
Start by creating a new Laravel project:

composer create-project laravel/laravel laravel-vue-crud
cd laravel-vue-crud

Step 2: Configure the Database
Set up your .env file with database credentials:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=crud_app
DB_USERNAME=root
DB_PASSWORD=your_password

Step 3: Run Migrations
Prepare a migration for the CRUD table:

php artisan make:migration create_items_table

Edit the migration file to define your table schema:

Schema::create('items', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->text('description');
    $table->timestamps();
});

Run the migration:

php artisan migrate

2. Backend: Laravel API

Step 1: Create a Model and Controller
Generate the model and its controller:

php artisan make:model Item -mcr

Define CRUD methods in ItemController:

namespace App\Http\Controllers;

use App\Models\Item;
use Illuminate\Http\Request;

class ItemController extends Controller
{
    public function index()
    {
        return Item::all();
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
        ]);
        return Item::create($validated);
    }

    public function show(Item $item)
    {
        return $item;
    }

    public function update(Request $request, Item $item)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
        ]);
        $item->update($validated);
        return $item;
    }

    public function destroy(Item $item)
    {
        $item->delete();
        return response()->json(['message' => 'Item deleted successfully']);
    }
}

Step 2: Add API Routes
Define API endpoints in routes/api.php:

use App\Http\Controllers\ItemController;

Route::apiResource('items', ItemController::class);

3. Frontend: Vue.js Integration

Step 1: Install Vue
Install Vue using Laravel’s preset tools:

npm install
npm install vue@next vue-loader@next

Step 2: Configure Vue
Set up Vue in resources/js/app.js:

import { createApp } from 'vue';
import App from './components/App.vue';

const app = createApp(App);
app.mount('#app');

Create an App.vue component:

<template>
  <div>
    <h1>CRUD Application</h1>
    <item-list />
  </div>
</template>

<script>
import ItemList from './ItemList.vue';

export default {
  components: { ItemList },
};
</script>

Step 3: Create CRUD Components
Create a ItemList.vue component:

<template>
  <div>
    <h2>Items</h2>
    <form @submit.prevent="createItem">
      <input v-model="newItem.name" placeholder="Item name" required />
      <textarea v-model="newItem.description" placeholder="Item description"></textarea>
      <button type="submit">Add Item</button>
    </form>

    <ul>
      <li v-for="item in items" :key="item.id">
        <strong>{{ item.name }}</strong>
        <p>{{ item.description }}</p>
        <button @click="editItem(item)">Edit</button>
        <button @click="deleteItem(item.id)">Delete</button>
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      items: [],
      newItem: {
        name: '',
        description: '',
      },
    };
  },
  methods: {
    async fetchItems() {
      const response = await axios.get('/api/items');
      this.items = response.data;
    },
    async createItem() {
      const response = await axios.post('/api/items', this.newItem);
      this.items.push(response.data);
      this.newItem = { name: '', description: '' };
    },
    async deleteItem(id) {
      await axios.delete(`/api/items/${id}`);
      this.items = this.items.filter(item => item.id !== id);
    },
    async editItem(item) {
      const updatedItem = await axios.put(`/api/items/${item.id}`, item);
      const index = this.items.findIndex(i => i.id === item.id);
      this.$set(this.items, index, updatedItem.data);
    },
  },
  mounted() {
    this.fetchItems();
  },
};
</script>

4. Compile Assets

Compile the frontend assets:

npm run dev

5. Test Your Application

  • Start the Laravel server:
    php artisan serve
  • Open the app in your browser at http://127.0.0.1:8000.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete