Efaz Efaz - 2 months ago 39
PHP Question

How to check user status while login in laravel 5.3?

I have used Laravel Authentication (Quickstart). But I need to check the status of the user (approved/pending). If not approved, then an error will be shown in the login page. I need to know in which file I have to make the change and what is the change. Currently I am working on Laravel 5.3.

Answer

You can create a Laravel Middleware check the link for additional info

php artisan make:middleware CheckStatus

modify your middleware to get

<?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_field != 'approved'){
            Auth::logout();
            return redirect('/login')->with('erro_login', 'Your error text');
        }
        return $response;
    }
}

then add your middleware to your Kernel.php

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

and finally add the middleware to your route

Route::post('/login', [
    'uses'          => 'Auth\AuthController@login',
    'middleware'    => 'checkstatus',
]);

I hope it helps