Vue.js example in Laravel 7

By CodersDrive
04-Jul-2020
Laravel 7
Vue.js

Vue.Js will be very handy to build HTML elements as DOM (Document Object Model) in your web application, because by changing the structure at a single Vue.js template, will be reflected in your entire application. Also they can be reused where ever required just with its template name.

Example: Display Clients as Vue.js objects

Firstly you need to have clients data for which we will create a Vue component. For development purpose you can get dummy clients data using Faker as per the below article.

Once the Vue.js is scaffolded to your application edit the file app.js present at resources/js/ and add a new Vue component ClientComponent.vue as shown below.

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue');

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 * Eg. ./components/ExampleComponent.vue -> 
 */

// const files = require.context('./', true, /\.vue$/i)
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))

Vue.component('example-component', require('./components/ExampleComponent.vue').default);
Vue.component('client', require('./components/ClientComponent.vue').default);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

const app = new Vue({
    el: '#app',
});

Now create the file ClientComponent.vue at resources/js/components/ location and add the following code.

<template>
    <div class="card shadow zoom" style="width:350px">
    
    <div class="card-body">
      <h4 class="card-title border rounded p-1 shadow-sm bg-success"><span class="fa fa-user mr-3"/><b>{{client.firstName}} {{client.lastName}}</b></h4>
      <h5 class="ml-2"><span class="fa fa-envelope mr-1"/>{{client.email}}</h5>
      <h5 class="ml-2"><span class="fa fa-mobile-alt mr-1"/>{{client.phoneNumber}}</h5>
      <h6 class=" text-center border p-1 rounded text-white bg-primary"><span class="fa fa-map-marker-alt"/><br>{{client.address}}, {{client.city}}, {{client.country}}.</h6>
     
    </div>

    </div>
</template>


<script>
    export default {
        mounted() {
            console.log('Component mounted.')
        },
        props:['client'],
    }
</script>

Let's try to understand what this template contain. Our main objective is to create 'Bootstrap Card' CSS for every client to display his/her details on a web page. This part we want to make it as Vue template. If you observe at the code the required 'Bootstrap Card' code is placed between <template></template>. At every part of card where client fileds are to be displayed will be marked with vue variables like {{client.firstName}} will display the firstName field from the Client data. client will be the variable property to be passed to this template when using it. We can use this template just like a normal HTML tag as<client></client>.

Note that before we use this template in your application you have to compile this using the following command.

npm run watch

When ever you are working on Vue template run this command on a separate terminal which will convert all your .vue components updates on the fly to app.js available at public/js/.

Now add a route to web.php present at routes/ as below. Which means when ever /client-vue-list url is accessed clients data will be fetched using ClientController.

Route::get('/client-vue-list', 'ClientController@show_vue');

Create a ClientController using the following command.

php artisan make:controller ClientController

Once the Controller is created successfully open the file ClientController.php present at app/Http/Controllers/ and add the following code.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Client;

class ClientController extends Controller
{
    
    public function show_vue()
    {
        $clients= Client::all();
        return view('client-vue', compact('clients'));
    }

}

Now create a view file client-vue.blade.php at resources/views/ and add the following code.

@extends('layouts.app')
<style>
.zoom {
  transition: transform 0.2s;
  margin: 0 auto;
}

.zoom:hover {
  /* IE 9 */
  /* Safari 3-8 */
  transform: scale(1.06);
}

</style>
@section('content')

<div class="container">
<h1 class="text-center">Vue.js demo Clients view</h1>
    <div id="app" class="row">

        @foreach($clients as $client)
        <div class="col-lg-4 col-md-6 col-sm-12 p-1">

            <client :client="{{$client}}"></client>
    
        </div>
        @endforeach
    </div>

</div>


@endsection

This page contains the <client :client="{{$client}}"></client> HTML tag which is a vue template created earlier, to this client data is passed to :client property of Vue template.

Thats all! your clients view page is ready as shown below. Also you can check the Demo link.

Vue.js clients example Demo

The main advantage of using Vue is when ever you want to add a new field to client details view just add that field in ClientComponent.vue. Not only fields you can change its style also from here.


Laravel 7 Vue.js

Search blog..!

Connect with us