php - Add middleware after login in laravel

984

I am using laravel for my web application,in login I am asking for username ,password and I want to check the email of the logged in user is verified or not. If the verified status is 0 I want to sent the error message to the login page using the verifiedemail named middleware.

route.php

Route::group(['middleware' => 'auth', 'superadmin'], function () {
    Route::resource('/users', 'UserController'); 
});
Route::get('/', function () {
    if (Auth::guest())
        return view('/auth/login');
    else
        return redirect('/tests');
});
Route::resource('/tests', 'TestController');
Route::get('/sites', '[email protected]'); 
Auth::routes();
Route::get('/home', '[email protected]');

Redirectedifauthenticated.php <--- middleware file

public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->check()) {
        return redirect('/home');
    }
    return $next($request);
}

verifiedemail.php <--- middleware file

public function handle($request, Closure $next)
{
    if ( Auth::check() && Auth::user()->isVerifiedEmail() )
    {
        return redirect('/login');
    }
    return $next($request);
}

kernel.php

 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,
        'superadmin' => 'App\Http\Middleware\SuperAdmin',
        'verifiedemail' => 'App\Http\Middleware\VerifiedEmail',
    ];
}

I think these are the files where i have to change but what and where I have to change that's the question for me .please help thanks in advance.

284

Answer

Solution:

If you're using the default laravel authentication you can add a listener on theIlluminate\Auth\Events\Attempting which is fired on every login attempt and do your validation in the listener.

More about fired event on Auth

More about event listeners

People are also looking for solutions to the problem: php - Hierarchical directory structure in mysql database

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.