How to Install Vue.js using Laravel UI?

How to Install Vue.js using Laravel UI?

If you are don't know how to install Vue.js in Laravel 6 then I will help you to Laravel install Vue.js using Laravel UI. We will also install vue with Laravel and also Laravel 6 Vue Auth using Laravel UI.

If you are don't know how to install Vue.js in Laravel 6 then I will help you to Laravel install Vue.js using Laravel UI. We will also install vue with Laravel and also Laravel 6 Vue Auth using Laravel UI.

If you are beginner with Laravel 6 then I am sure I can help you to install Vue in Laravel 6. It's very simple way to install using Laravel UI composer package.

Laravel UI provide way to install bootstrap, vue and react setup. They also provide auth scaffold for login and register. Laravel 6 provide easy way to work with bootstrap, Vue and React.

If you want to install vue in your laravel 6 project then install following laravel ui composer package to get command:

composer require laravel/ui

After successfully install above package then we are ready to install vue with our application.

we can install two way, one is a simple vue setup install and another is install vue with auth. So let's see both way.

Install Vue
php artisan ui vue
Install Vue with auth
php artisan ui vue --auth

Now we installed vue, you can see your resource directory js folder. it will be like as bellow screen shot:

You also need to install npm and run it. so let's run both command:

Install NPM
npm install
Run NPM
npm run dev

Now you can work with your vue app.

I hope it can help you...

Full Stack Vue.js & Laravel - How to use Vuejs Service Container Package

Full Stack Vue.js & Laravel - How to use Vuejs Service Container Package

In this full stack vue.js to Laravel tutorial explains how to use of the vuejs service container package. Laravel to Vue.js ~ Full Stack Vue.js & Laravel Integration (Vuejs Service Container Package)

In this full stack vuejs to laravel tutorial, we cover a wide array of topics ~ all of which circle around the use of the vuejs service container package (https://github.com/zhorton34/vue-service-container).

Order of topics we'll cover:
1: Installing the vue service container
2: Creating the vuejs service container
3: Injecting Php data into vue service container, utilizing laravel blade
4: Accessing the php content from within vuejs service container
5: Creating vuejs service providers (boot, register, afterLaunch, & when hooks - context object)
6. Creating a global Vue component within the welcome-page.js ServiceProvider
6: Laravel blade templates & vuejs templates within a single template
7. Configuring webpack aliases using webpack.mix.js
8: Implementing vuex store within service provider
9: Committing php data to vuex store BEFORE we mount our Vue instance to the DOM
10: Global Event Bus Service Provider
11: Filters vuejs Service Provider
12: Directives vuejs Service Provider
13: Implementing vue-router using a vuejs Service Provider
14: afterLaunch, hook into vue-router example
15: Code splitting (definition)
16: Code splitting (purpose)
17: Full Stack Laravel and vuejs code splitting implementation
18: Closing Thoughts

How to use Vue Router to create Laravel and Vue CRUD forms

How to use Vue Router to create Laravel and Vue CRUD forms

In this Laravel tutorial, we will learn to use Vue Router and the v-form package to create Laravel and Vue CRUD forms. We will create a Single Page Application(SPA) using Laravel and Vue.js

In this tutorial i am going to create Laravel and Vue js crud tutorial. We will create a Single Page Application(SPA) using the Laravel and Vue.js. This tutorial you will learn how to use vue router and v-form package to create laravel vue js crud.

In Todays, Most popular JS Framework are Angular JS and Vue JS. Angular JS and Vue JS are a very user friendly JS Framework and most popular. It provides to manage whole project or application without refresh page and powerful jquery validation.

In this post i going to lean how to create CRUD(Create, Read, Update and Delete) application with pagination using Laravel 6. In this example i added "User Management" with you can do several option like as bellow:

1. User Listing

2. User Create

3. User Edit

4. User Delete

I will show you how to use JavaScript moment js and how to use Vue filter, Vue progressbar, Vue router to complete this single page application.

you can implement crud application from scratch, so no worry if you can implement through bellow simple step. After create successful example, you will find layout as bellow:

Preview: User Table

Preview: Add User Modal

Preview: Error message before submit non-validate data

Preview: Edit modal window

Preview: Edit modal window with error message

Step 1: Laravel Installation

In first step, If you haven't installed Laravel in your system then you have to run bellow command and get fresh Laravel project.

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

Step 2: Create items table and model

In this step i will use User model and users table to create vue js laravel crup single page application. So paste this below code to your users table.

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{

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

    public function down()
    {
        Schema::dropIfExists('users');
    }
}

After create "usres" table you should create Item model for items, so first create file in this path app/User.php and put bellow content in user.php file:

app/User.php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    protected $guarded = [];

}

Now run migration command after setup your database.

Step 3: Define the API routes

Now, we need to define the API routes inside the **routes >> api.php **file.

routes/api.php

//Vue js Api Route

Route::apiResources(
	[
		'user' => 'API\UserController'
	]
);

Step 4: Create Controller

To quickly generate an API resource controller that does not include the create or edit methods, use the --api switch when executing the make:controller command:

php artisan make:controller API/UserController --api

Ok, now we have created new controller as UserController in this path app/Http/Controllers/API/UserController.php. this controller will manage all route method:

Step 5 : Setup Laravel Mix

Now copy your js and scss file inside assets folder like below.

Now open webpack.mix.js which is located inside your root directory.

webpack.mix.js

mix.js('resources/assets/js/app.js', 'public/js/app.js')
   .sass('resources/assets/sass/app.scss', 'public/css/app.css')
   .version();

Step 6 : Install Vue dependency and edit configurations

Now, go inside the project folder and install the frontend dependencies using the following command.

npm install

Now run following command, you can visit vue official documentation

npm install vue-router

Now we are going to install vue-progressbar. We will use it when a user created then progressbar will be shown in top of our application. Now run following command, you can visit vue progressbar official documentation

npm install vue-progressbar

Now we have to install moment js in our app to format date like laravel carbon function. You can visit moment js official documentation

npm install moment --save

Now we have to install v-form for client side validation. Read their documentation to learn more how to use it and how v-form works.

npm i axios vform

Now last is sweet alert 2. Now run below command to install it. You can visitofficial documentation.Now run command to compile our all JavaScript file.

npm install watch

Now create folder and file like below image.

Step 7: Setup js file

resources/assets/js/app.js

require('./bootstrap');

window.Vue = require('vue');

//Import Vue Filter
require('./filter'); 

//Import progressbar
require('./progressbar'); 

//Setup custom events 
require('./customEvents'); 

//Import View Router
import VueRouter from 'vue-router'
Vue.use(VueRouter)

//Import Sweetalert2
import Swal from 'sweetalert2'
window.Swal = Swal
const Toast = Swal.mixin({
  toast: true,
  position: 'top-end',
  showConfirmButton: false,
  timer: 3000,
  timerProgressBar: true,
  onOpen: (toast) => {
    toast.addEventListener('mouseenter', Swal.stopTimer)
    toast.addEventListener('mouseleave', Swal.resumeTimer)
  }
})
window.Toast = Toast

//Import v-from
import { Form, HasError, AlertError } from 'vform'
window.Form = Form;
Vue.component(HasError.name, HasError)
Vue.component(AlertError.name, AlertError)

//Routes
import { routes } from './routes';

//Register Routes
const router = new VueRouter({
    routes, 
    mode: 'hash',

})

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

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

resources/assets/js/customEvents.js

This is our custom events generator code. You can see its documentation to know better.

//Setup our custom events in vue

let Fire = new Vue()
window.Fire = Fire;

resources/assets/js/filter.js

//Vue Filter to make first letter Capital
Vue.filter("strToUpper", function(text) {

	return text.charAt(0).toUpperCase() + text.slice(1);

});

//Vue moment js to show human readable date
import moment from "moment"; //Import Moment

Vue.filter("formatDate", function(date) {

	return moment(date).format('MMMM Do YYYY');

}); 

resources/assets/js/progressbar.js

import VueProgressBar from 'vue-progressbar';

Vue.use(VueProgressBar, {
  color: 'rgb(143, 255, 199)',
  failedColor: 'red',
  height: '4px',
  transition: {
    speed: '0.4s',
    opacity: '0.6s',
    termination: 300
  },
})

resources/assets/js/routes.js

import Dashboard from './components/admin/DashboardComponent.vue'
import Profile from './components/admin/ProfileComponent.vue'
import User from './components/admin/UserComponent.vue'

export const routes = [
    {
        path:'/dashboard',
        component:Dashboard
    },
    {
        path:'/profile',
        component:Profile
    },
    { 
        path:'/users',
        component:User
    },

];

Step 8 : Setup Controller

App\Http\Controllers\API\UserController.php


namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;

class UserController extends Controller
{

    public function index()
    {
        return User::latest()->get();
    }

    public function store(Request $request)
    {   
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required',
            'type' => 'required',
        ]);

        return User::create([
           'name' => $request['name'],
           'email' => $request['email'],
           'password' => \Hash::make($request['password']),
           'type' => $request['type'],
        ]);
    }

    public function show($id)
    {
        //
    }

    public function update(Request $request, $id)
    {   
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required',
            'type' => 'required',
        ]);

        $user = User::findOrFail($id);

        $user->update($request->all());
    }

    public function destroy($id)
    {
        $user = User::findOrFail($id);
        $user->delete();
        return response()->json([
         'message' => 'User deleted successfully'
        ]);
    }
}

Step 9: Create Blade File

In this step we have to create only one blade file that will manage create, update and delete operation of items module with vue js.In this file i added jquery, bootstrap js and css, vue.js, vue-resource.min.js, toastr js and css for notification in this blade file.

resources/views/master.blade.php


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="x-ua-compatible" content="ie=edge">

  <title>Vue js App</title>
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <link rel="stylesheet" href="{{ mix('css/app.css') }}">
</head>

<body class="hold-transition sidebar-mini">
<div class="wrapper" id="app">

  <aside class="main-sidebar sidebar-dark-primary elevation-4">
    <div class="sidebar">
      <nav class="mt-2">
        <ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false">
     
            <li class="nav-item">
            <router-link to="/dashboard" class="nav-link">
                <i class="nav-icon fas fa-tachometer-alt blue"></i>
                <p>
                Dashboard

                </p>
            </router-link>
            </li>

          <li class="nav-item has-treeview">
            <a href="#" class="nav-link">
              <i class="nav-icon fa fa-cog green"></i>
              <p>
                Management
                <i class="right fa fa-angle-left"></i>
              </p>
            </a>
            <ul class="nav nav-treeview">
              <li class="nav-item">
                <router-link to="/users" class="nav-link">
                  <i class="fas fa-users nav-icon"></i>
                  <p>Users</p>
                </router-link>
              </li>

            </ul>
          </li>
     
          <li class="nav-item">
                <router-link to="/profile" class="nav-link">
                    <i class="nav-icon fas fa-user orange"></i>
                    <p>
                        Profile
                    </p>
                </router-link>
         </li>

        </ul>
      </nav>
    </div>
  </aside>

  <div class="content-wrapper">
    <div class="content">
      <div class="container-fluid">

        <router-view></router-view>

        <vue-progress-bar></vue-progress-bar>

      </div>
    </div>
  </div>

</div>

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

resources/assets/js/components/admin/UserComponent.vue


<template>
    <div class="container">
        <div class="row mt-5">
          <div class="col-md-12">
            <div class="card">
              <div class="card-header">
                <h3 class="card-title">Users Table</h3>

                <div class="card-tools">
                    <button class="btn btn-success" data-toggle="modal" data-target="#addNew" @click="openModalWindow">Add New <i class="fas fa-user-plus fa-fw"></i></button>
                </div>
              </div>
             
              <div class="card-body table-responsive p-0">
                <table class="table table-hover">
                  <tbody>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Type</th>
                        <th>Registered At</th>
                        <th>Modify</th>
                  </tr> 

                  <tr v-for="user in users" :key="user.id">
                    <td>{{ user.id }}</td>
                    <td>{{ user.name }}</td>
                    <td>{{ user.email }}</td>
                    <td>{{ user.type | strToUpper}}</td>
                    <td>{{ user.created_at | formatDate}}</td>

                    <td>
                        <a href="#" data-id="user.id" @click="editModalWindow(user)">
                            <i class="fa fa-edit blue"></i>
                        </a>
                        |
                        <a href="#" @click="deleteUser(user.id)">
                            <i class="fa fa-trash red"></i>
                        </a>

                    </td>
                  </tr>
                </tbody></table>
              </div>
            
              <div class="card-footer">
                 
              </div>
            </div>
           
          </div>
        </div>


            <div class="modal fade" id="addNew" tabindex="-1" role="dialog" aria-labelledby="addNewLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
                <div class="modal-content">
                <div class="modal-header">

                    <h5 v-show="!editMode" class="modal-title" id="addNewLabel">Add New User</h5>
                    <h5 v-show="editMode" class="modal-title" id="addNewLabel">Update User</h5>

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                    </button>
                </div>

<form @submit.prevent="editMode ? updateUser() : createUser()">
<div class="modal-body">
     <div class="form-group">
        <input v-model="form.name" type="text" name="name"
            placeholder="Name"
            class="form-control" :class="{ 'is-invalid': form.errors.has('name') }">
        <has-error :form="form" field="name"></has-error>
    </div>

     <div class="form-group">
        <input v-model="form.email" type="email" name="email"
            placeholder="Email Address"
            class="form-control" :class="{ 'is-invalid': form.errors.has('email') }">
        <has-error :form="form" field="email"></has-error>
    </div>
    

    <div class="form-group">
        <input v-model="form.password" type="password" name="password" id="password" placeholder="Enter password"
        class="form-control" :class="{ 'is-invalid': form.errors.has('password') }">
        <has-error :form="form" field="password"></has-error>
    </div>

    <div class="form-group">
        <select name="type" v-model="form.type" id="type" class="form-control" :class="{ 'is-invalid': form.errors.has('type') }">
            <option value="">Select User Role</option>
            <option value="admin">Admin</option>
            <option value="user">Standard User</option>
            <option value="author">Author</option>
        </select>
        <has-error :form="form" field="type"></has-error>
    </div>

</div>
<div class="modal-footer">
    <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
    <button v-show="editMode" type="submit" class="btn btn-primary">Update</button>
    <button v-show="!editMode" type="submit" class="btn btn-primary">Create</button>
</div>

</form>

                </div>
            </div>
            </div>
    </div>

</template>

<script>
    export default {
        data() {
            return {
                editMode: false,
                users: {},
                form: new Form({
                    id: '',
                    name : '',
                    email: '',
                    password: '',
                    type: '',

                })
            }
        },
        methods: {
        
        editModalWindow(user){
           this.form.clear();
           this.editMode = true
           this.form.reset();
           $('#addNew').modal('show');
           this.form.fill(user)
        },
        updateUser(){
           this.form.put('api/user/'+this.form.id)
               .then(()=>{

                   Toast.fire({
                      icon: 'success',
                      title: 'User updated successfully'
                    })

                    Fire.$emit('AfterCreatedUserLoadIt');

                    $('#addNew').modal('hide');
               })
               .catch(()=>{
                  console.log("Error.....")
               })
        },
        openModalWindow(){
           this.editMode = false
           this.form.reset();
           $('#addNew').modal('show');
        },

        loadUsers() {

        axios.get("api/user").then( data => (this.users = data.data));
          //data ene users object a rakhlam then loop a users print

        },

        createUser(){

            this.$Progress.start()

            this.form.post('api/user')
                .then(() => {
                   
                    Fire.$emit('AfterCreatedUserLoadIt'); //custom events

                        Toast.fire({
                          icon: 'success',
                          title: 'User created successfully'
                        })

                        this.$Progress.finish()

                        $('#addNew').modal('hide');

                })
                .catch(() => {
                   console.log("Error......")
                })

     

            //this.loadUsers();
          },
          deleteUser(id) {
            Swal.fire({
              title: 'Are you sure?',
              text: "You won't be able to revert this!",
              icon: 'warning',
              showCancelButton: true,
              confirmButtonColor: '#3085d6',
              cancelButtonColor: '#d33',
              confirmButtonText: 'Yes, delete it!'
            }).then((result) => {
                
              if (result.value) {
                //Send Request to server
                this.form.delete('api/user/'+id)
                    .then((response)=> {
                            Swal.fire(
                              'Deleted!',
                              'User deleted successfully',
                              'success'
                            )
                    this.loadUsers();

                    }).catch(() => {
                        Swal.fire({
                          icon: 'error',
                          title: 'Oops...',
                          text: 'Something went wrong!',
                          footer: '<a href>Why do I have this issue?</a>'
                        })
                    })
                }

            })
          }
        },

        created() { //Like Mounted this method
            this.loadUsers();

            Fire.$on('AfterCreatedUserLoadIt',()=>{ //custom events fire on
                this.loadUsers();
            });

            // setInterval(() => 
            //     this.loadUsers()
            // ,3000); //Every 3 seconds loadUsers call
        }
    }
</script> 

Now every thing is done. Now you are ready to check it. Hope it will help you.

PHP variable to JavaScript In Laravel

PHP variable to JavaScript In Laravel

In PHP, there is always a limitation on pass PHP variable to the javascript file. Many PHP developers, face this issue. But Laravel has one package which is directly set the variable in js. So, you can use this package for passing a variable from controller to javascript.

In PHP, there is always a limitation on pass PHP variable to the javascript file. Many PHP developers, face this issue. But Laravel has one package which is directly set the variable in js. So, you can use this package for passing a variable from controller to javascript.

However, we know the Laravel framework is having the largest community. Similarly, Laravel having large package base. So, sometimes it is easy to use package rather use custom code. Moreover, you can use existing packages.

Pass PHP variable to JavaScript

Many times you often find the need to pass PHP variable or string to the javascript file. But for this, you can use the below package.

Install package

Just copy below package and paste into the composer.json file.

"laracasts/utilities": "^2.1"

Or similarly from command line or terminal run command:

composer require laracasts/utilities

Provider

Further, add the Service provider into the config/app.php file. Which is used for the binding. After this, you will get Javascript facade.

'providers' => [
    '...',
    'Laracasts\Utilities\JavaScript\JavaScriptServiceProvider'
];

Publish the Configuration:

Finally, publish the config using the below command.

php artisan vendor:publish --provider="Laracasts\Utilities\JavaScript\JavaScriptServiceProvider"

Further, it will copy the javascript.js file to the config folder. There are two variable you can assign the values. Firstly, you can set bind_js_vars_to_this_view. This will set the name of the view. Basically, this is a partial view. If more than one view then you can set in array. Secondly, js_namespace is where you can define the namespace of the js variable. By default, Laracasts is the variable but you can change it to something else.

Usage in controller

Import the Dependency

You can initialize the JavaScript variable in the controller. Initialize and import into the controller.

use Javascript;

Set Variable

Now, you can define the variable into the controller using Javascript. You can set the values in the key-value pair. Assign a value to the key.

$array = [
    'key' => value_here,
];
 
JavaScript::put($array);

So, put your value into the JavaScript variable using the value of an array. Once you define into the array and assign to the variable you can access it into the js file.

Now, your controller will look like below.

<?php
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use JavaScript;
 
class VarController extends Controller
{
 
 
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        \JavaScript::put([
            'foo' => 'bar',
            'user' => 'user',
            'time' => '2019-04-29'
        ]);
        return view('pages/home');
    }
}

Access In JS file

Now, your blade file will look like below.

@extends('layouts.default')
@section('content')
    <div style="text-align:center">
        <h1>PHP var to JavaScript</h1>
         
    </div>
     
@stop
@section('scripts')
<script src='assets/app.js'></script>
@stop

In js file, you can access the set variable into the Laracasts namespace. Which you define in the javascript.js file.

console.log(Laracasts.foo); // access foo variable
console.log(Laracasts.user);// access user variable
console.log(Laracasts.time);// access time variable

In this way, you can directly access the set variable. This will give simple access for getting value into the js file. There is a limitation for getting the value into the js file. So this package will give you direct access into js file.

In many cases, this will give you the simplest solution. Many developers have to face this problem in developement. So, this post will give some relief from this problem. Let me know if you face any issue.

Thanks For Visiting, Keep Visiting. If you liked this post, share it with all of your programming buddies!