building-a-crud-application-with-laravel-and-vuejs.html

Building a CRUD Application with Laravel and Vue.js

Creating a CRUD (Create, Read, Update, Delete) application is a fundamental exercise for any developer looking to enhance their skills. In this article, we will walk you through building a simple CRUD application using Laravel as the backend and Vue.js for the frontend. By the end of this guide, you will understand how to set up a full-stack application that effectively manages data.

What is CRUD?

CRUD stands for Create, Read, Update, and Delete. It represents the four basic operations that can be performed on data stored in a database. Here's a quick overview of what each operation does:

  • Create: Adding new records to the database.
  • Read: Retrieving existing records from the database.
  • Update: Modifying existing records.
  • Delete: Removing records from the database.

Why Choose Laravel and Vue.js?

Laravel

Laravel is a popular PHP framework that simplifies the development process by providing a robust structure and built-in functionalities such as routing, authentication, and database management. Its elegant syntax and extensive documentation make it a favorite among developers.

Vue.js

Vue.js is a progressive JavaScript framework used for building user interfaces. It is lightweight, flexible, and integrates well with other libraries, making it the perfect choice for developing dynamic frontend applications.

Setting Up Your Environment

Before diving into coding, ensure you have the following tools installed:

  • PHP (7.3 or higher)
  • Composer (Dependency manager for PHP)
  • Node.js and npm (Node package manager)
  • Laravel (Install via Composer)
  • Vue CLI (Install globally using npm)

Installing Laravel

To create a new Laravel project, run the following command in your terminal:

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

Setting Up the Database

  1. Create a new database in your preferred database management system (MySQL, PostgreSQL, etc.).
  2. Update your .env file with the database credentials:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password
  1. Run migrations to set up the default tables:
php artisan migrate

Building the Backend with Laravel

Creating the Model and Migration

We will create a simple application to manage tasks. First, create a model and migration file for the Task entity:

php artisan make:model Task -m

In the generated migration file (database/migrations/xxxx_xx_xx_create_tasks_table.php), define the fields:

public function up()
{
    Schema::create('tasks', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('description')->nullable();
        $table->timestamps();
    });
}

Run the migration:

php artisan migrate

Creating the Controller

Next, create a resource controller to handle CRUD operations:

php artisan make:controller TaskController --resource

In app/Http/Controllers/TaskController.php, implement the methods for each CRUD operation:

public function index()
{
    return Task::all();
}

public function store(Request $request)
{
    $task = Task::create($request->validate([
        'title' => 'required|string|max:255',
        'description' => 'nullable|string',
    ]));

    return response()->json($task, 201);
}

public function show(Task $task)
{
    return $task;
}

public function update(Request $request, Task $task)
{
    $task->update($request->validate([
        'title' => 'required|string|max:255',
        'description' => 'nullable|string',
    ]));

    return response()->json($task);
}

public function destroy(Task $task)
{
    $task->delete();
    return response()->json(null, 204);
}

Setting Up Routes

Define API routes in routes/api.php:

Route::apiResource('tasks', TaskController::class);

Building the Frontend with Vue.js

Setting Up Vue.js

Navigate to your project directory and install Vue.js:

npm install vue

Create a new Vue component for managing tasks. In resources/js, create a file named TaskComponent.vue:

<template>
    <div>
        <h1>Task List</h1>
        <form @submit.prevent="addTask">
            <input v-model="newTask.title" placeholder="Task Title" required />
            <textarea v-model="newTask.description" placeholder="Task Description"></textarea>
            <button type="submit">Add Task</button>
        </form>
        <ul>
            <li v-for="task in tasks" :key="task.id">
                <h3>{{ task.title }}</h3>
                <p>{{ task.description }}</p>
                <button @click="deleteTask(task.id)">Delete</button>
            </li>
        </ul>
    </div>
</template>

<script>
export default {
    data() {
        return {
            tasks: [],
            newTask: { title: '', description: '' },
        };
    },
    methods: {
        fetchTasks() {
            fetch('/api/tasks')
                .then(response => response.json())
                .then(data => {
                    this.tasks = data;
                });
        },
        addTask() {
            fetch('/api/tasks', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(this.newTask),
            })
            .then(response => response.json())
            .then(data => {
                this.tasks.push(data);
                this.newTask = { title: '', description: '' };
            });
        },
        deleteTask(id) {
            fetch(`/api/tasks/${id}`, { method: 'DELETE' })
            .then(() => {
                this.tasks = this.tasks.filter(task => task.id !== id);
            });
        }
    },
    mounted() {
        this.fetchTasks();
    }
};
</script>

Integrating Vue.js into Laravel

In resources/js/app.js, import and register the component:

import { createApp } from 'vue';
import TaskComponent from './TaskComponent.vue';

createApp(TaskComponent).mount('#app');

Compiling Assets

Run the following command to compile your assets:

npm run dev

Conclusion

Congratulations! You've successfully built a CRUD application using Laravel and Vue.js. This application allows users to create, read, update, and delete tasks seamlessly.

Key Takeaways

  • Laravel provides an efficient backend structure for managing database operations.
  • Vue.js allows for dynamic and responsive frontend user interfaces.
  • Integrating both frameworks can lead to powerful web applications.

As you continue to develop your skills, consider expanding this application by adding features like user authentication, validation, or real-time updates using Laravel Echo and Pusher. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.