Login System in Laravel and VueJs

In this post we have learn how to create Login System in Laravel and VueJs.

Login System in Laravel and VueJs

route/web.php

Route::get("vue_js/register","VueController@register")->name("vue_js/register");
Route::get("vue_js/login","VueController@login")->name("vue_js/login");
Route::post("vue_js/save_user","VueController@save_user")->name("vue_js/save_user");
Route::post("vue_js/country","VueController@country")->name("vue_js/country");
Route::post("vue_js/state","VueController@state")->name("vue_js/state");
Route::post("vue_js/checkuser","VueController@checkuser")->name("vue_js/checkuser");
Route::get("vue_js/user_list","VueController@user_list")->name("vue_js/user_list");
Route::post("vue_js/fetch_user","VueController@fetch_user")->name("vue_js/fetch_user");
Route::get("vue_js/logout","VueController@logout")->name("vue_js/logout");

Create controller file : VueController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\User;
class VueController extends Controller
{

function register(){
 if(session()->get('loged_in')){
  return redirect()->route("vue_js/user_list");
 }else{
  $country_list = DB::table('countries')->orderBy('country_name')->get();
  return view ("vue_js/register")->with('country_list', $country_list);
 }
}

function country(Request $request){
  $data = DB::table('states')
   ->where('country_id',$request->country_id)
   ->get();
  return response()->json($data);
}

function state(Request $request){
  $data = DB::table('cities')
   ->where('state_id',$request->state_id)
   ->get();
  return response()->json($data);
}

public function save_user(Request $request)
{
 $request->validate([
  'fnm' => 'required',
  'lnm' => 'required',
  'email' => 'required|email|unique:users,email',
  'pwd' => 'required|min:6',
  'cpwd' => 'required_with:pwd|same:pwd|min:6',
  'gender' => 'required',
  'img' => 'required',
  'country' => 'required',
  'state' => 'required',
  'city' => 'required'
]);

$data = new User;
  $image = $request->file('img');
  $imgname = time() . $image->getClientOriginalName();
  $image->move(public_path('images'), $imgname);
  $data->fnm = $request->fnm;
  $data->lnm = $request->lnm;
  $data->email = $request->email;
  $data->pwd = $request->pwd;
  $data->gender = $request->gender;
  $data->img = $imgname;
  $data->country = $request->country;
  $data->state = $request->state;
  $data->city = $request->city;
  if($data->save()){
   return redirect(route("vue_js/login"));
  }
}

function login(){
 if(session()->get('loged_in')){
  return redirect()->route("vue_js/user_list");
 }else{
  return view("vue_js/login"); 
 }
}

function checkuser(Request $request){
 $request->validate(
  array(
   "email" => 'required|email',
   "pwd" => "required"
 ));

$data = new User;
$user = $data->where(array("email" => $request->email,"pwd" => $request->pwd))->get();
if(!empty($user[0]['email'])){
 session()->put('loged_in', $user[0]['email']);
 return response()->json(['success' => 'successfully login'], 200);
}else{
 return response()->json(['fail' => 'Wrong Email Or Password'], 422);
}
}

function user_list(){
 if(session()->get('loged_in')){
  return view("vue_js/user_list");
 }
 else{
  return redirect()->route("vue_js/login");
 }
}

function fetch_user(Request $request){
 $data = new User;
 if(!empty($request->search)){
  $search = $request->search;
  $user = $data->where('fnm','like','%'.$search.'%')
   ->orwhere('lnm','like','%'.$search.'%')
   ->orwhere('email','like','%'.$search.'%')
   ->orwhere('gender','like','%'.$search.'%')
   ->get();
  return json_encode($user);
 }else{
  $user = $data->get();
  return json_encode($user);
 }
}

function logout(){
 if(session()->get('loged_in')){
  session()->forget('loged_in');
  return redirect()->route("vue_js/login");
 }else{
  return redirect()->route("vue_js/login"); 
 }
}

}

vue_js/register.blade.php

<html>
<head>
<title>Register</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div class="container mt-5" id='myapp'>
<h2 class="text-center">Register form</h2>
<center><i class="error alert-md alert-danger"></i></center>
<form id="user_form" action="save_user" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="fnm">First Name:</label>
<input type="text" class="form-control " id="fnm" placeholder="Enter first name" name="fnm" v-model='fnm'> 
</div>

<div class="form-group">
<label for="lnm">Last Name:</label>
<input type="text" class="form-control " id="lnm" placeholder="Enter last name" name="lnm" v-model='lnm'> 
</div>

<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="email" placeholder="Enter email" name="email" v-model='email'>
</div>

<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd" v-model='pwd'>
</div>

<div class="form-group">
<label for="cpwd">Confirm Password:</label>
<input type="password" class="form-control" id="cpwd" placeholder="Enter confirm password" name="cpwd" v-model='cpwd'>
</div>

<div class="form-group">
<label for="gender">Gender:</label>
<input type="radio" name="gender" value="Male" v-model='gender'>Male
<input type="radio" name="gender" value="Female" v-model='gender'>Female
</div>

<div class="form-group">
<label for="img">Image:</label>
<input type="file" class="form-control" id="file" name="file" v-on:change="onImageChange" accept="image/*">
</div>

<div class="form-group">
<label for="country">Country:</label>
<select name="country" id="country" class="form-control" v-model='country' v-on:change="getCountry($event);">
<option value="">Select Country</option>
@foreach($country_list as $country)
<option value="{{ $country->country_id}}">{{ $country->country_name }}</option>
@endforeach
</select>
</div>

<div class="form-group">
<label for="state">State:</label>
<select name="state" id="state" class="form-control" v-model='state' v-on:change="getState($event);">
<option value="">Select State</option>
<option v-for='data in states' v-bind:value='data.state_id'>@{{ data.state_name }}</option>
</select>
</div>

<div class="form-group">
<label for="city">City:</label>
<select name="city" id="city" class="form-control" v-model='city'>
<option value="">Select City</option>
<option v-for='data in cities' v-bind:value='data.city_id'>@{{ data.city_name }}</option>

</select>
</div>

<button type="button" id="submit" class="btn btn-primary" v-on:click="adduser();">Register</button>
<a href="{{route('vue_js/login')}}" class="btn btn-primary ml-5">Login</a>
<br /><br /><br /><br />
</form>
</div>
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var app = new Vue({
el: '#myapp',
data: {
fnm: "",
lnm: "",
email: "",
pwd:"",
cpwd:"",
gender:"",
img: "",
country:"",
state:"",
city:"",
states: "",
cities: ""
},
methods: {
onImageChange:function(event){
console.log(event.target.files[0]);
this.img = event.target.files[0];
},
getCountry: function(){
axios.post('country', {
country_id: this.country
})
.then(function (response){
app.states = response.data;
});
},
getState: function(){
axios.post('state', {
state_id: this.state
})
.then(function (response){
app.cities = response.data;
});
},
adduser: function(){
const config = {
headers: { 'content-type': 'multipart/form-data' }
}
let formData = new FormData();
formData.append('fnm', this.fnm);
formData.append('lnm', this.lnm);
formData.append('email', this.email);
formData.append('pwd', this.pwd);
formData.append('cpwd', this.cpwd);
formData.append('gender', this.gender);
formData.append('img', this.img);
formData.append('country', this.country);
formData.append('state', this.state);
formData.append('city', this.city);
axios.post('save_user', formData, config )
.then(function (response) {
if(response.status === 200){
window.location.href = "login";
} 
})
.catch(function (error) {
var er = error.response.data.errors;
if(er.fnm){
$(".error").text(er.fnm);
this.fnm.focus();
}else if(er.lnm){
$(".error").text(er.lnm);
this.lnm.focus();
}else if(er.pwd){
$(".error").text(er.pwd);
this.pwd.focus();
}else if(er.cpwd){
$(".error").text(er.cpwd);
this.cpwd.focus();
}else if(er.gender){
$(".error").text(er.gender);
this.gender.focus();
}else if(er.img){
$(".error").text(er.img);
this.img.focus();
}else if(er.country){
$(".error").text(er.country);
this.country.focus();
}else if(er.state){
$(".error").text(er.state);
this.state.focus();
}else if(er.city){
$(".error").text(er.city);
this.city.focus();
}
});
}
}
});
</script>
</body>
</html>

vue_js/login.blade.php

<!DOCTYPE html>
<html lang="en">
 <head>
  <title>Login</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.20.0/axios.min.js" ></script>
 </head>
<body>

 <div class="container mt-5" id="myapp">
   <h2 class="text-center">Login form</h2>
   <form action="check_user" method="post">
   @csrf

   <div class="form-group">
    <label for="email">Email:</label>
    <i class="email alert-md alert-danger"></i>
    <input type="text" class="form-control" id="email" placeholder="Enter email" name="email" v-model="email">
  </div>

  <div class="form-group">
    <label for="pwd">Password:</label>
    <i class="pwd alert-md alert-danger"></i>
    <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd" v-model="pwd">
  </div>

   <button type="button" class="btn btn-primary" v-on:click="checkUser();">Login</button>
   <a href="{{route('vue_js/register')}}" class="btn btn-primary ml-5">Register</a>
 </form>
 </div>
</body>
<script>
var app = new Vue({
  el:"#myapp",
    data:{
    email:"",
    pwd:""
  },
  methods:{
   checkUser: function(){
    axios.post("checkuser",{
     email:this.email,
     pwd:this.pwd
   })
  .then(function(response){
   if(response.status === 200)
   {
   // alert(response.data.success);
    window.location.href ="user_list";
  }
   console.log(response);
 })
 .catch(function(error){
   if(error.response.data.fail){
   alert(error.response.data.fail);
 }
var er = error.response.data.errors;
  if(er.email){
    $(".email").text(er.email);
  }else if(er.pwd){
   $(".pwd").text(er.pwd);
  }

  });
 }
 }
});
</script>
</html>

vue_js/user_list.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
 <title>User List</title>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>

<div class="container mt-5" id="myapp">
<h2 class="text-center">User Table</h2><br />
<a href="{{ route("vue_js/logout") }}" class="btn btn-primary float-right">Logout</a>
<br /><br />
<input type="text" class="form-control" name="search" v-on:keyup="getrecord($event);" placeholder="Search..." /><br />
<table class="table table-dark table-striped">
<thead>
 <tr>
  <th>Firstname</th>
  <th>Lastname</th>
  <th>Email</th>
  <th>Gender</th>
 </tr>
 </thead>
<tbody>
<tr v-for='user in users'>
  <td>@{{ user.fnm }}</td>
  <td>@{{ user.lnm }}</td>
  <td>@{{ user.email }}</td>
  <td>@{{ user.gender }}</td>
</tr>
</tbody>
</table>
</div>
<script>
 var app = new Vue({
  el: '#myapp',
   mounted:function(){
   this.allRecords() //method1 will execute at pageload
  },
data: {
 users: "",
 search:""
},
methods: {
 allRecords: function(){
 axios.post('fetch_user',{
})
.then(function (response) {
 app.users = response.data;
})
.catch(function (error) {
 console.log(error);
});
},
getrecord: function(event){
var search = event.target.value;
axios.post('fetch_user',{
search:search
})
.then(function (response) {
app.users = response.data;
})
.catch(function (error) {
console.log(error);
});
}

}
})
</script>
</body>
</html>