The Ultimate Guide to Implement Vue JS in Laravel

The Ultimate Guide to Implement Vue JS in Laravel

What is Vue JS?

Vue is a progressive framework for creating impressive user interfaces. If looked at its core, it is focused on the view layer of an application.

Integrating Vue JS with various other platforms or existing applications is quite simple.

It is extensible, simple, interesting, and innovative to create single web page applications.

Data binding is a big problem for the front-end world. Now, we are more focused on data instead of micromanaging the DOM as we used to do with Jquery in the past. Vue has the amazing capability of handling this easily with a two-way reactive data binding system.

Why should we use Vue JS with Laravel?

Vue JS allows the Laravel developers to create the front end in a way that their application does not have to reload the page every time an update is made.

Vue helps you create a full-scale application that is event-driven and has all activity completely handled on the frontend. But it also offers composable components that can be used as the user wishes to use them.

Since Vue JS integrates well with Laravel, developers require making only a few trips to request data from their Laravel application and create changes just by switching components without reloading the page.

When your software application is created with Vue components, the dependencies of every component are automatically tracked at the time it is rendered. Due to this, the system knows precisely which component actually requires to be updated when there is a change in the existing data.

Vuejs permits Laravel developers to create an optimal single-page application that is easy to operate. As the complete assets of the application get loaded at once and make it simple to use the application comfortably and in an easier manner.

Vue.js is an easy platform to adopt as a developer. It offers you very few options that make you feel like a sophisticated developer, on the other hand, has a lot to offer in an abstract way.

Another interesting thing about Vue is that your valid HTML is also a valid Vue template. You can keep your CSS external or you can directly process it with Javascript depending on your application requirements.

Also read: Top 5 reasons to use Vue js for your next web application project

Moreover, you can also take advantage of scoped styling, to apply style changes to a single component on the fly without the change affecting other components.

How to implement Vue js in Laravel:

    • Make Laravel Project by below command:

      composer create-project --prefer-dist laravel/laravel vueJs-in-Laravel

      Add below code to package.json file.

      “devDependencies”: {
      “Vue”: “^2.5.7”
      }

      Change the .env file as per your database.
      Run npm install in the terminal.

    • Create API CRUD for users.

      Add below code to database/migrations/create_users_table.php file.

         Schema::create('users', function (Blueprint $table) {
                  $table->id();
                  $table->string('name');
                  $table->string('email')->unique();
                  $table->timestamp('email_verified_at')->nullable();
                  $table->string('password');
                  $table->rememberToken();
                  $table->timestamps();
          });
      

      Run below command for migration:

      php artisan migrate

      Make Controller by below command:

      php artisan make controller:UserController

      Also read: React.js vs Vue.js – The Key Difference of Popular Frameworks

      Add below code to app/Http/Controllers/UserController.php file.

      <?php
      
      namespace App\Http\Controllers;
      
      use App\User;
      use Illuminate\Http\Request;
      use App\Http\Resources\UserCollection;
      use Illuminate\Support\Facades\Hash;
      use Illuminate\Support\Facades\DB;
      use Illuminate\Support\Facades\Validator;
      
      class UserController extends Controller
      {
          public function getUsers()
          {
              //Get Users list
              $user = User::orderBy('created_at', 'desc')->paginate(5);
              if(empty($user)){
                  return false;
              }
              return UserCollection::collection($user);
          }
      
          public function deleteUser($id)
          {
              //Delete User
              $user = User::findOrFail($id)->delete();
              if(empty($user)){
                  return false;
              }
      
              return $user;
          }
      
          public function addUser(Request $request)
          {
      
              //validation for inputs
              $validator = Validator::make($request->all(), [
                  'name' => 'required',
                  'email' => 'required|email'
              ]);
              $return['message'] = 'Please enter valid inputs';
              if ($validator->fails()) {
                  return $return;
              }
      
              //Add user
              $user = new User();
              $user->name = $request->name;
              $user->email = $request->email;
              $user->password = Hash::make(rand(10000, 99999));
              $user->save();
              return $user;
          }
      
          public function editUser(Request $request)
          {
              //validation for inputs
              $validator = Validator::make($request->all(), [
                  'name' => 'required',
                  'email' => 'required|email'
              ]);
              $return['message'] = 'Please enter valid inputs';
              if ($validator->fails()) {
                  return $return;
              }
      
              //Update user
              DB::table('users')->where('id', $request->id)->update(['name' => $request->name]);
              return true;
          }
      }
      

      Add below code to routes/api.php file.

      Route::get('users', 'UserController@getUsers');
      Route::delete('deleteUser/{id}', 'UserController@deleteUser');
      Route::post('addUser', 'UserController@addUser');
      Route::put('editUser', 'UserController@editUser');
      

  • Implement Vue js to Laravel

    Create directory components in resources/js directory.
    Create Users.vue file in that and add below code into it.

    <template>
        <div>
            <h2>
                Users
            </h2>
            <form @submit.prevent="addUser" class="mb-3">
                <div class="form-group">
                    <input type="text" class="form-control" placeholder="Name" v-model="user.name">
                </div>
                <div class="form-group">
                    <input type="email" class="form-control" placeholder="EMail" v-model="user.email">
                </div>
                <button type="submit" class="btn btn-info btn-block">Save</button>
            </form>
            <nav aria-label="Page navigation example">
                <ul class="pagination">
                    <li v-bind:class="[{disabled: !pagination.prev_page_url}]" class="page-item">
                        <a class="page-link" href="#" @click="fetchUsers(pagination.prev_page_url)">Previous</a>
                    </li>
                    <li class="page-item disabled"><a class="page-link test-dark" href="#">Page {{ pagination.current_page
                        }} of {{ pagination.last_page }}</a></li>
                    <li v-bind:class="[{disabled: !pagination.next_page_url}]" class="page-item">
                        <a class="page-link" href="#" @click="fetchUsers(pagination.next_page_url)">Next</a>
                    </li>
                </ul>
            </nav>
            <div class="card card-body mb-2" v-for="user in users" v-bind:key="user.id">
                <h3>{{ user.name }}</h3>
                <p>{{ user.email }}</p>
                <hr>
                <button @click="editUser(user)" class="btn btn-warning mb-2">Edit</button>
                <button @click="deleteUser(user.id)" class="btn btn-danger">Delete</button>
            </div>
        </div>
    </template>
    
    <script>
        export default {
            data() {
                return {
                    users: [],
                    user: {
                        id: '',
                        name: '',
                        email: '',
                        password: ''
                    },
                    user_id: '',
                    pagination: {},
                    edit: false
                }
            },
    
            created() {
                this.fetchUsers();
            },
    
            methods: {
                fetchUsers(page_url) {
                    let vm = this;
                    page_url = page_url || 'api/users'
                    fetch(page_url)
                        .then(res => res.json())
                        .then(res => {
                            this.users = res.data;
                            vm.makePagination(res.meta, res.links);
                        })
                        .catch(err => console.log(err));
                },
                makePagination(meta, links) {
                    let pagination = {
                        current_page: meta.current_page,
                        last_page: meta.last_page,
                        next_page_url: links.next,
                        prev_page_url: links.prev
                    }
                    this.pagination = pagination;
                },
                deleteUser(id) {
                    if (confirm('Are you sure?')) {
                        fetch("api/deleteUser/" + id, {
                            method: 'delete'
                        })
                            .then(res => res.json())
                            .then(data => {
                                alert('User deleted successfully.');
                                this.fetchUsers();
                            })
                            .catch(err => console.log(err));
                    }
                },
                addUser() {
                    if (this.edit === false) {
                        //Add
                        fetch('api/addUser', {
                            method: 'post',
                            body: JSON.stringify(this.user),
                            headers: {
                                'content-type': 'application/json'
                            }
                        })
                            .then(res => res.json())
                            .then(data => {
                                if (data.message) {
                                    alert(data.message);
                                } else {
                                    this.user.name = '';
                                    this.user.email = '';
                                    alert('User Added Successfully');
                                }
                                this.fetchUsers();
                            })
                    } else {
                        //Update
                        fetch('api/editUser', {
                            method: 'put',
                            body: JSON.stringify(this.user),
                            headers: {
                                'content-type': 'application/json'
                            }
                        })
                            .then(res => res.json())
                            .then(data => {
                                if (data.message) {
                                    alert(data.message);
                                } else {
                                    this.user.name = '';
                                    this.user.email = '';
                                    alert('User Updated Successfully');
                                }
                                this.fetchUsers();
                            })
                    }
                },
                editUser(user) {
                    this.edit = true;
                    this.user.id = user.id;
                    this.user.user_id = user.id;
                    this.user.name = user.name;
                    this.user.email = user.email;
                }
            }
        }
    </script>
    

    Also read: How to Create Rest API in Laravel 6 Using Passport?

    Open the resporces/js/app.js file and add the below code to it.

    require('./bootstrap');
    window.Vue = require('vue');
    Vue.config.devtools = false;
    Vue.component('navbar', require('./components/Navbar.vue').default);
    Vue.component('articles', require('./components/articles.vue').default);
    Vue.component('users', require('./components/Users.vue').default);
    const app = new Vue({
    el: '#app'
    });

    Create resources/js/Navbar.vue file and add the below code into it.

    <template>
        <nav class="navbar navbar-expand-sm navbar-dark bg-info mb-2">
            <div class="container">
                <a href="#" class="navbar-brand">LaraVue</a>
            </div>
        </nav>
    
    </template>
    

    Run below command for build:

    npm run watch

    Run below command for serve:

    php artisan serve

Conclusion:

In this guide, we learn how Vue.js works with Laravel. We explored some reasons why you should use Vue.js with Laravel. There are so many other things you can build with Laravel. Vue.js is very easy to use and works well with Laravel. This combination of Vue.js and Laravel is trending.

If you are looking to use Vue.js and Laravel combinations in your next project, then we are happy to help you. As a leader of Vue.js app development companies in India, we cater to Vue.js web development services to a wide array of clients across the globe. Hire our dedicated Vue.js developers to create innovative front-end, single-page apps, financial software, and healthcare apps.

Mobio Solutions is a Business technology Solutions company who will guide you with strategic advice on the technology that fits best to your business solution. You can contact and get a 1-week free consultation service from the best technocrat of the team.