Skip to main content

LARAVEL 5x CHECK STATUS ACTIVE BEFORE LOGIN

LARAVEL 5x CHECK STATUS ACTIVE BEFORE LOGIN


For this tutorial we are using laravel 5.4 and we will add validation to user login that if user status is active then user can login otherwise if user status is not active then show error to user. so follow the below steps.



The best way to add status validation is through a middleware to check status . so we are creating middleware and we will use it in loginController.

Run the following command in console or cmd to create checkStatus middleware .
 
php artisan make:middleware CheckStatus


after completion of command "Middleware created successfully" will show.

then paste the below code into file .

<?php

namespace App\Http\Middleware;

use Closure;

use Illuminate\Support\Facades\Auth;

class CheckStatus

{

    /**

     * Handle an incoming request.

     *

     * @param  \Illuminate\Http\Request  $request

     * @param  \Closure  $next

     * @return mixed

     */

    public function handle($request, Closure $next)

    {

        $response = $next($request);

        //If the status is not approved redirect to login 

        if(Auth::check() && Auth::user()->status != '1'){

            Auth::logout();

            $request->session()->flash('alert-danger', 'Your Account is not activated yet.');

            return redirect('/login')->with('erro_login', 'Your error text');

        }

        return $response;

    }

}


Our middleware is ready to use. to register our middleware open kernel.php(yourProjectFolder\app\Http\kernal.php) and search $routeMiddleware and add
 
'checkstatus' => \App\Http\Middleware\CheckStatus::class,
 

So after adding the above line your $routeMiddleware will look like

 protected $routeMiddleware = [

        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,

        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,

        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,

        'can' => \Illuminate\Auth\Middleware\Authorize::class,

        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,

        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

        'checkstatus' => \App\Http\Middleware\CheckStatus::class,

    ];



 Now everything is done you just need to add middleware into login controller so open LoginController(yourProjectFolder\app\Http\Controller\LoginController)   and in construct function add middleware like below code:-
    
    
    public function __construct()

    {

        $this->middleware(['guest','checkstatus'])->except('logout');

    }

   
After adding middleware your loginController will look like

<?php



namespace App\Http\Controllers\Auth;



use App\Http\Controllers\Controller;

use Illuminate\Foundation\Auth\AuthenticatesUsers;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;





class LoginController extends Controller

{

    use AuthenticatesUsers;



    protected $redirectTo = '/dashboard';



    public function __construct()

    {

        $this->middleware(['guest','checkstatus'])->except('logout');

    }

}



OR you can add middleware from routes.php Example
 
 
Route::get('/dashboard', function() {

    return view('admin.layout');

})->middleware(['auth','checkStatus']);


To show Error on your view file you can add

 
<div class="flash-message">

    @foreach (['danger', 'warning', 'success', 'info'] as $msg)

      @if(Session::has('alert-' . $msg))



      <p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }} <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a></p>

      @endif

    @endforeach

  </div> <!-- end .flash-message -->




  Now run your application and check login it will check status before login and show error if status!=1 you can change this validation into middleware according to your requirements. :)

Thank You.

Comments

  1. Hey! This is my first visit to your blog! We are
    a collection of volunteers and starting
    a new project in a community in the same niche. Your blog provided us beneficial information to work on. You have done a marvellous job!

    React Native Development Company
    Reactjs Development Company Texas

    ReplyDelete
  2. If you're looking to lose weight then you absolutely need to get on this totally brand new personalized keto diet.

    To create this keto diet service, licensed nutritionists, fitness couches, and top chefs joined together to develop keto meal plans that are useful, suitable, price-efficient, and delicious.

    Since their first launch in January 2019, hundreds of people have already completely transformed their figure and health with the benefits a certified keto diet can give.

    Speaking of benefits: clicking this link, you'll discover 8 scientifically-confirmed ones provided by the keto diet.

    ReplyDelete
  3. As stated by Stanford Medical, It is really the SINGLE reason this country's women get to live 10 years longer and weigh an average of 19 kilos less than us.

    (And by the way, it has absolutely NOTHING to do with genetics or some secret diet and really, EVERYTHING about "HOW" they are eating.)

    P.S, I said "HOW", and not "what"...

    Tap on this link to find out if this brief questionnaire can help you decipher your real weight loss potential

    ReplyDelete

Post a Comment

Popular posts from this blog

Run and compile sass scss file to css using node

  Today we learn how to use scss and generate css using node  or Run and compile sass scss file to css using node   So please follow simple  steps :-   Today we will create a project that can read scss file and generates css with it  Note: Make sure you have installed node in your system. If you want to help to install node js based on your system then check our other tutorial or check node js official website. Now create a blank folder and open  terminal(linux) or cmd(windows) and navigate to your current project folder by using cd command Now run below command npm init after enter it will ask you some package info that you can fill according to you or just keep enter until it finished. The above command will generate package.json file Now  we will install npm module that will convert our scss to css Run below command: npm install node-sass So we have installed node-sass package . Now open package.json file in your editor and add below code into it into

How to retrieve Facebook Likes, share , comment Counts

function facebook_count($url){     // Query in FQL     $fql  = "SELECT share_count, like_count, comment_count ";     $fql .= " FROM link_stat WHERE url = '$url'";     $fqlURL = "https://api.facebook.com/method/fql.query?format=json&query=" . urlencode($fql);     // Facebook Response is in JSON     $response = file_get_contents($fqlURL);     return json_decode($response); } $fb = facebook_count('https://www.facebook.com/BahutHoGyiPadhai'); // facebook share count echo $fb[0]->share_count;  echo "like"; // facebook like count echo $fb[0]->like_count ; echo "comment"; // facebook comment count echo $fb[0]->comment_count;  ?>

jQuery Datatable add date range filter

jQuery Datatable add date range filter Datatable is most useful jQuery plugin that helps to make our html tables more powerful and give powers to user to filter , search, sort, pagination etc, But Data table provides a common filter only and yes we can customize and add filter for each column, but still sometimes we need an advance filter like show results only between a date range, So today we will learn how to create a minimum and maximum date range fields and show date picker on it, and user can fill dates by selecting dates and data table will auto filter records based on it. Keep follow below steps :- I am using Bootstrap if you want to use any other framework then you can use. Create a new index.php file  and paste below code in it, i have used all required CDN like bootstrap, datatable, datepicker etc. <!DOCTYPE html> <html> <head>     <title>Datatable Date Range Filter Example</title>     <link rel="stylesheet" href="https://maxcd