Build Crud App with Laravel and Vue.js

By Sumeet Shroff
Last Updated On : February 28, 2023
Build Crud App with Laravel and Vue.js

To start building a CRUD app with Laravel and Vue.js, we need to have a basic understanding of both frameworks. Laravel is a PHP framework that provides an elegant and expressive syntax for web application development. It comes with various features like routing, middleware, controllers, and database migrations. On the other hand, Vue.js is a JavaScript framework that enables us to build interactive user interfaces and single-page applications. Now, let's take a closer look at each step of building a laravel and vue CRUD.

1. **Setting up a Laravel Project:

To set up a new Laravel project, we can use the Laravel installer or Composer. If we have the Laravel installer installed, we can run the following command in the terminal:

laravel new project-name

This command will create a new Laravel project with the name "project-name". If we don't have the Laravel installer, we can use Composer to create a new project. We can run the following command in the terminal:

composer create-project --prefer-dist laravel/laravel project-name

This command will create a new Laravel project with the name "project-name" using the latest stable version of Laravel.

2. Creating a Controller and Model:

Once we have our Laravel project set up, we can create a new controller and model for our CRUD app. We can use the following commands to create a new controller and model:

php artisan make:controller ItemController --resource
php artisan make:model Item -m

The first command will create a new controller called "ItemController" with the "--resource" flag. The "--resource" flag will create the controller with the CRUD methods: index, create, store, show, edit, update, and destroy. The second command will create a new model called "Item" with the "-m" flag. The "-m" flag will create a migration file for the model. We will use the migration file to create the database table for our CRUD app.

3. Creating the Database Table:

To create the database table for our CRUD app, we can use Laravel's migration feature. We can open the migration file created by the "make:model" command and define the table columns and their data types. For example, if we want to create a table for items with the columns "name", "description", and "price", we can define the migration file as follows:

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

This migration will create a table called "items" with the columns "id", "name", "description", "price", and the default timestamps "created_at" and "updated_at". After defining the migration file, we can run the migration to create the table in the database:

php artisan migrate

4. Creating Views with Vue.js:

To create the views for our CRUD app, we can use Vue.js. We can create a separate Vue.js component for each view, such as the create form, edit form, and the list view. For example, we can create a component called "ItemList" to display the list of items in the database table:

<template>
    <div>
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Description</th>
                    <th>Price</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="item in items" :key="item.id">
                    <td>{{ item.name }}</td>
                    <td>{{ item.description }}</td>
                    <td>{{ item.price }}</td>
                    <td>
                        <router-link :to="'/edit/' + item.id">Edit</router-link>
                        <button @click="deleteItem(item.id)">Delete</button>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</template>

In this example, we have created a table to display the list of items in the database. We have used the v-for directive to loop through the items array and display the item details in each row of the table. We have also used the router-link component to create a link to the edit form for each item, and a button to delete the item.

5. Creating Routes:

To handle the requests for our CRUD app, we need to create routes in Laravel. We can create the routes in the “routes/web.php” file. For example, we can create the following routes for our CRUD app:

Route::get('/', 'ItemController@index');
Route::get('/create', 'ItemController@create');
Route::post('/store', 'ItemController@store');
Route::get('/edit/{id}', 'ItemController@edit');
Route::post('/update/{id}', 'ItemController@update');
Route::delete('/delete/{id}', 'ItemController@destroy');

These routes will handle the requests for the list view, create form, store action, edit form, update action, and delete action, respectively.

6. Handling Requests in the Controller:

To handle the requests for our CRUD app, we need to define the corresponding methods in the controller we created earlier. In our case, we have created an “ItemController” with the CRUD methods. For example, we can define the “index” method to return the list of items:

public function index()
{
    $items = Item::all();
    return view('items.index', compact('items'));
}

In this method, we have retrieved all the items from the “Item” model and passed them to the “items/index” view. Similarly, we can define the other methods in the controller to handle the create, store, edit, update, and delete actions.

7. Creating Vue Components for Forms:

To handle the create and edit forms in our CRUD app, we need to create Vue.js components. We can create a separate component for each form, such as the “ItemCreate” and “ItemEdit” components. For example, we can create the “ItemCreate” component as follows:

<template>
    <div>
        <form @submit.prevent="saveItem">
            <div>
                <label>Name:</label>
                <input type="text" v-model="item.name">
            </div>
            <div>
                <label>Description:</label>
                <textarea v-model="item.description"></textarea>
            </div>
            <div>
                <label>Price:</label>
                <input type="text" v-model="item.price">
            </div>
            <button type="submit">Save</button>
        </form>
    </div>
</template>
<script>
export default {
    data() {
        return {
            item: {
                name: '',
                description: '',
                price: ''
            }
        }
    },
    methods: {
        saveItem() {
            axios.post('/store', this.item)
                .then(response => {
                    this.$router.push('/');
                })
                .catch(error => {
                    console.log(error);
                });
        }
    }
}
</script>

In this component, we have defined a form with the input fields for the item name, description, and price. We have used the “v-model” directive to bind the input values to the” item” object. We have also defined the “saveItem” method to submit the form data to the Laravel backend using the “axios” library.

8. Integrating Vue Components with Laravel Views:

To integrate the Vue.js components with Laravel views, we need to include the Vue.js scripts in the Laravel views. We can use the mix method provided by Laravel to compile and bundle the Vue.js components. For example, we can include the “app.js” file in the “app.blade.php” file as follows:

<!DOCTYPE html>
<html>
    <head>
        <title>@yield('title')</title>
        <link rel="stylesheet" href="{{ mix('/css/app.css') }}">
    </head>
    <body>
        <div>
            @yield('content')
        </div>
        <script src="{{ mix('/js/app.js') }}"></script>
    </body>
</html>

In this file, we have included the “app.js” file, which contains the compiled Vue.js components, in the “<script>” tag. We have also defined a “<div>” element with the “id” attribute of "app," which will be used to mount the Vue.js components.

9.** Mounting Vue Components:

To mount the Vue.js components on the Laravel views, we need to define the routes for the Vue.js components in the app.js file. For example, we can define the routes for the ItemIndex, ItemCreate, and ItemEdit components as follows:

import ItemIndex from './components/ItemIndex.vue';
import ItemCreate from './components/ItemCreate.vue';
import ItemEdit from './components/ItemEdit.vue';
const routes = [
    { path: '/', component: ItemIndex },
    { path: '/create', component: ItemCreate },
    { path: '/edit/:id', component: ItemEdit }
];
const router = new VueRouter({
    mode: 'history',
    routes: routes
});
const app = new Vue({
    router: router
}).$mount('#app');

In this file, we have imported the "ItemIndex," "ItemCreate," and "ItemEdit" components, and defined the routes for these components using the VueRouter library. We have also created a new Vue instance and mounted it on the ‘<div>’ element with the id attribute of "app."

Conclusion**:

In this article, we have learned how to build a CRUD app with Laravel and Vue.js. We have covered the following topics:

    - Setting up the Laravel Project - Creating a MySQL Database and Model - Creating Laravel Views - Creating Vue Components for the List View - Creating Routes - Handling Requests in the Controller - Creating Vue Components for Forms - Integrating Vue Components with Laravel Views - Mounting Vue Components
By following these steps, you can build your own CRUD app with Laravel and Vue.js.

Categories

Latest Blogs

Ready to Amplify Your Services with our Premium White Label Web Design

Are you looking to expand your service offerings without the overhead of an in-house design team? Our white label web design services are the perfect solution. We provide top-notch, fully customizable web designs that seamlessly blend with your brand, allowing you to offer additional value to your clients.
Contact Us Today to Start Partnering with Our White Label Web Design Experts!
© 2024 · Prateeksha Web Design. Built with Gatsby All rights reserved | Privacy Policy
Designed by Prateeksha Web