AngularJS Login Logout with Laravel 6

  • 28-03-2022
  • 1176
  • Angular JS
  • Haresh Chauhan

Hello guys in this tutorial, we will make AngularJS Login Logout With Laravel 6 System. Before to do this example we require to Laravel 6 Setup with Angularjs. If you have a setup of Laravel 6 with Angular JS then It's good. Otherwise, you can install setup from following this link. Laravel 6 installation with Angular

Here, We are creating the task use of Laravel 6 ,Web Services (API) and AngularJS. use of these three elements through we are performing the task.

AngularJS Login Logout with Laravel 6 system. In this example is the basic level task So, It's easy for you. This Login Logout system easy to customize. So, Now we are performing this task.

AngularJS Login Logout with Laravel 6

Step 1 : Set Routes into app.js

In this first step we require to change into app.js, Put this routes into file save it.

public/js/app.js

var myApp = angular.module('myApp', ['ngRoute', 'ngCookies', 'angularSoundManager']);

myApp.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {

   /*======================= Login =======================*/
   $routeProvider.when('/login', {
      title: 'Login',
      templateUrl: 'public/templates/user/login.html',
      controller: 'userController',
      login: true
   });
   /*======================= Login  =======================*/

   /*======================= Dashboard =======================*/
   $routeProvider.when('/dashboard', {
      title: 'dashboard',
      templateUrl: 'public/templates/home/dashboard.html',
      controller: 'userController',
      login: true
   });
   /*======================= Dashbaord =======================*/

}]);

Step 2 : Create Login Form

Here, we need to make login form into public/templates/user/login.html directory. To, Copy this code and paste it.

public/templates/user/login.html

<div class="container">
   <div class="text-center">
      <form class="login" name="loginForm" ng-submit="doLogin(loginForm)">
         <h2 class="text-uppercase1">Login</h2>
         <div class="form-group text-left mt-4">
            <label>Email</label>
             <input type="email" name="email" ng-model="email" placeholder="Email" class="form-control">
         </div>
         <div class="form-group text-left">
            <label>Password</label>
            <input type="password" name="password" ng-model="password" class="form-control" placeholder="Password">
         </div>
         <div class="form-group">
            <input type="submit" name="save" class="btn btn-pink" value="Login">
         </div>
      </form>
   </div>
</div>

Step 3 : Put code into userController.js

Here, In this step we require to change into app.js file. So, Now copy that file and put it.

rosources/assets/js/controllers/userController.js

myApp.controller('userController', ['$scope', '$location', 'userModel', '$cookies', function ($scope, $location, userModel, $cookies) {
   var user = userModel.getUserObject();
   if (user) {
      var token = user.data.data.token;
      var user = user;
   } else {
      var token = '';
      var user = '';
   }


   if ($cookies.get("activation")) {
      var activate = $cookies.get("activation");
   } else {
      var activate = '';
   }

   $scope.activates = activate;


   angular.extend($scope, {
      /*======================== Start Login ============================*/
      doLogin: function (loginForm) {
         var data = {
            email: $scope.email,
            password: $scope.password
         };
         userModel.doLogin(data);
      },
      /*======================== End Login ============================*/

      /*======================== Logout User ============================*/
      doLogout: function () {
         userModel.doUserLogout();
         $location.path('/');
      },
      /*======================== Logout User ============================*/

   });

}]);

Step 4 : Put Code into userModel.js

In this 4th step we will change into userModel.js. So let's do that.

rosources/assets/js/models/userModel.js

myApp.factory('userModel', ['$http', '$location', '$cookies', function ($http, $location, $cookies) {
   /*======================== Start Defining Variable ============================*/
   var userModel = {};
   /*======================== End Defining Variable ============================*/

   /*======================== Start Login ============================*/
   userModel.doLogin = function (loginData) {
      return $http({
         headers: {
            'Content-Type': 'application/json'
         },
         url: 'http://localhost:8000/api/login',
         method: 'POST',
         data: {
            email: loginData.email,
            password: loginData.password
         }
      }).then(function (response) {
         if (response.data.response == false) {
            toastr.error(response.data.message);
         } else {
            $cookies.put('auth', JSON.stringify(response));
            $location.path('/dashboard');
         }
      });
   };
   /*======================== End Login ============================*/

   /*======================== Start Logout User ============================*/
   userModel.doUserLogout = function(){
      return $http({
         headers : {
            'Content-Type' : 'application/json'
         },
         url : http://localhost:8000/logout,
         method : 'GET',

      }).then(function (response){
            $cookies.remove('auth');
            $location.path('/');
         }
         });
   };
   /*======================== End Logout User ============================*/

   /*======================== Start Get Login User DATA ============================*/
   userModel.getUserObject = function () {
      var userObj = angular.fromJson($cookies.get('auth'));
      return userObj;
   };
   /*======================== End Get Login User DATA ============================*/

   return userModel;
}]);

Step 5 : Create A UserController

Now, We require to make a one UserController.php.So, Let's run this command.

php artisan make:controller API\UserController

Step 6 : Add route in api.php file

In this step we must need to create routes for login API.So, let's added routes into api.php.

routes/api.php

<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
   Route::post('login','UserController@login');
   Route::get('logout','UserController@logout']);

Step 7 : UserController.php

Now, We need to added code into UserController.php file. So, let's do first copy this code and put in your controller file.

App/Http/Controllers/API/UserController.php

<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Validator;
use Auth;

class UserController extends Controller {    
    
    public function __construct() {
        /* code here */
    }

    /* ************************************************ */
    /* Login */
    public function checkLogin(Request $request) {
        error_reporting(0);

        $input = $request->all();

        $validator = Validator::make($input,[            
            'email'=>'required|email|exists:front_user',
            'password'=>'required',
        ]);

        if ($validator->fails()) {
            $data       = array();
            $message    = $validator->errors()->first();
            $response   = false;
            return response()->json([$data,$message,$response]);
        }

        $token = null;
        try {
            if(\Auth::guard('api')->attempt(['email' => $input['email'], 'password' => $input['password']])) {
                $user = \Auth::guard('api')->user();
                $token = $user->createToken('MyApp',['api'])->accessToken;
                $data['id']         = $user->id;
                $data['email']         = $user->email;
                $data['token']         = $token;
                return response()->json([$data,'login successfully',true]);
            }else{
                $message ='Email and Password are Wrong.';
                return response()->json($message);
            }
        } catch (\Exception $e) {
            return response()->json('Exception');
        }
    }

    /* ************************************************ */
    /* Logout */
    public function logout() {
        try {
            if (\Auth::check()) {
                $accessToken = Auth::user()->token();
                $id = Auth::user()->id;
                \DB::table('oauth_refresh_tokens')->where('access_token_id', $accessToken->id)->update(['revoked' => true]);
                $accessToken->revoke();
            }
            return response()->json(['','User successfully logout.',true]);
        }catch(\Exception $ex){
            return response()->json('Exception');  
        }
    }
}

Step 8 : Dashboard page

Here, We are create just dashboard page. So, Copy this code and put into dashboard.html file and save it.

public/templates/user/dashboard.html

<section>
   <h2>
      Hi, I am from webappfix.com
   </h2>
   <h3>It's your dashboard</h3>
   <a href="javascript:void(0)" class="" ng-click="doLogout()">Log out</a>
</section>

Now we are ready to run using quick command. So, follow this below command.

php artisan serve

Open Your browser and run this URL localhost:8000/#!/login.

I hope it can help you.

Thanks...


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :