Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check user status while login in Laravel 5?

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.

like image 312
Zaman Avatar asked Sep 28 '16 19:09

Zaman


2 Answers

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

like image 76
Camilo Rojas Avatar answered Sep 19 '22 04:09

Camilo Rojas


I found a simple solution for this. Artisan create App\Http\Controllers\Auth\LoginController, in this default controller just add this code if you have some conditions to login, for example I have a field state, you posibbly have status, email_status or other.

// Custom code for Auth process
protected function credentials( Request $request )
{
    $credentials = $request->only($this->username(), 'password');

    $credentials['state'] = 1;

    return $credentials;

}
like image 27
Aaron Nuñez Avatar answered Sep 19 '22 04:09

Aaron Nuñez