Creating a CRUD Application with Vue.js and Laravel

 Creating a CRUD Application with Vue.js and Laravel


In this blog post, we'll explore how to create a CRUD (Create, Read, Update, Delete) application with Vue.js and Laravel. We'll use Vue.js to build the frontend of the application, and Laravel to build the backend API that the frontend communicates with.


Prerequisites

Before we begin, you should have a basic understanding of Vue.js and Laravel. You should also have a development environment set up with both Vue.js and Laravel installed.


Setting Up the Application

Let's start by creating a new Laravel application using the following command:


javascript

Copy code

laravel new vue-laravel-crud

Once the application is created, navigate to the application directory and create a new Vue.js component:


bash


cd vue-laravel-crud

vue init webpack client

This will create a new Vue.js project in the client directory.


Next, we need to configure Laravel to serve our Vue.js application. Open up the routes/web.php file in your Laravel application, and add the following code:


php


Route::get('/', function () {

    return view('welcome');

});

Route::get('/{any}', function () {

    return view('welcome');

})->where('any', '.*');

In this code, we've added two routes: one for the root URL, and one for all other URLs. Both routes return the welcome view, which is a blank page.


Next, we need to update our Laravel application to serve the Vue.js application. Open up the resources/views/welcome.blade.php file, and replace the contents of the file with the following code:


html


<!DOCTYPE html>

<html>

    <head>

        <title>Laravel</title>

        <link rel="stylesheet" href="{{ mix('css/app.css') }}">

    </head>

    <body>

        <div id="app"></div>

        <script src="{{ mix('js/app.js') }}"></script>

    </body>

</html>

In this code, we've added a div element with an id of app, which is where our Vue.js application will be mounted. We've also included the CSS and JavaScript assets that were generated by the Vue.js CLI.


Building the CRUD Application

Now that we have our application set up, let's build the CRUD functionality.


Creating the API Routes

First, we need to create the API routes that the frontend will use to communicate with the backend. Open up the routes/api.php file in your Laravel application, and add the following code:


php

Copy code

Route::get('/products', 'ProductController@index');

Route::get('/products/{id}', 'ProductController@show');

Route::post('/products', 'ProductController@store');

Route::put('/products/{id}', 'ProductController@update');

Route::delete('/products/{id}', 'ProductController@destroy');

In this code, we've added routes for listing all products, getting a single product by ID, creating a new product, updating an existing product, and deleting a product.


Creating the Product Model and Controller

Next, we need to create the Product model and controller that will handle the CRUD functionality. Run the following command to create the Product model:


go


php artisan make:model Product -m

This will create a new Product model in the app/Models directory, as well as a new migration file in the database/migrations directory.


Next, run the following command to create the ProductController:


go


php artisan make:controller ProductController --api

This will create a new ProductController in the `app/Http/Controllers` directory.


Creating the Product Component

Now that we have our backend set up, let's create the frontend component that will allow us to interact with the API. Open up the client/src/components directory, and create a new file called Product.vue. Add the following code to the file:


html


<template>

    <div>

        <h1>Products</h1>

        <table>

            <thead>

                <tr>

                    <th>ID</th>

                    <th>Name</th>

                    <th>Description</th>

                    <th>Price</th>

                    <th>Actions</th>

                </tr>

            </thead>

            <tbody>

                <tr v-for="product in products" :key="product.id">

                    <td>{{ product.id }}</td>

                    <td>{{ product.name }}</td>

                    <td>{{ product.description }}</td>

                    <td>{{ product.price }}</td>

                    <td>

                        <button @click="editProduct(product)">Edit</button>

                        <button @click="deleteProduct(product)">Delete</button>

                    </td>

                </tr>

            </tbody>

        </table>

        <form v-if="showForm" @submit.prevent="saveProduct">

            <input type="text" v-model="product.name" placeholder="Name">

            <input type="text" v-model="product.description" placeholder="Description">

            <input type="number" v-model="product.price" placeholder="Price">

            <button type="submit">Save</button>

        </form>

        <button v-else @click="addProduct">Add Product</button>

    </div>

</template>


<script>

import axios from 'axios';


export default {

    data() {

        return {

            products: [],

            product: {

                name: '',

                description: '',

                price: 0

            },

            showForm: false

        }

    },

    created() {

        this.fetchProducts();

    },

    methods: {

        fetchProducts() {

            axios.get('/api/products')

                .then(response => {

                    this.products = response.data;

                })

                .catch(error => {

                    console.log(error);

                });

        },

        editProduct(product) {

            this.product = { ...product };

            this.showForm = true;

        },

        deleteProduct(product) {

            axios.delete(`/api/products/${product.id}`)

                .then(response => {

                    this.fetchProducts();

                })

                .catch(error => {

                    console.log(error);

                });

        },

        addProduct() {

            this.product = {

                name: '',

                description: '',

                price: 0

            };

            this.showForm = true;

        },

        saveProduct() {

            if (this.product.id) {

                axios.put(`/api/products/${this.product.id}`, this.product)

                    .then(response => {

                        this.showForm = false;

                        this.fetchProducts();

                    })

                    .catch(error => {

                        console.log(error);

                    });

            } else {

                axios.post('/api/products', this.product)

                    .then(response => {

                        this.showForm = false;

                        this.fetchProducts();

                    })

                    .catch(error => {

                        console.log(error);

                    });

            }

        }

    }

}

</script>

In this code, we've created a Vue.js component that lists all products in a table. Each row in the table has an "Edit" button and a "Delete" button that allow us to edit or delete a product. Clicking the "Add Product" button shows a form that allows us to add a new product.


Mounting the Component

Now that we have our component created, we need to mount it in our application. Open up client/src/App.vue and replace the existing code with the following:


html


<template>

  <div id="app">

    <Product />

  </div>

</template>


<script>

import Product from './components/Product.vue';


export default {

  name: 'App',

  components: {

    Product

  }

}

</script>

This code imports our Product component and mounts it inside the App component. Save the file and start up the application by running npm run serve in the client directory.


Now, if you visit http://localhost:8080, you should see a table listing all the products that were added to the database. Clicking the "Edit" or "Delete" buttons will allow you to edit or delete a product, and clicking the "Add Product" button will show a form that allows you to add a new product.


Conclusion

In this tutorial, we learned how to create a simple full-stack web application using Vue.js and Laravel. We created a simple API using Laravel's built-in functionality, and we created a Vue.js component that allowed us to interact with the API. By combining these two technologies, we were able to create a functional web application that allows us to view, edit, and delete products.




No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...