简体   繁体   中英

Additional auth middleware in Laravel 5.4

I want to add additional middleware to user model. User table has row 'approved' which is boolean (default is false). So when user logins - middleware should check if 'approved' is equal to true. If not, redirect to error page. What i got so far:

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class ConfirmedMiddleware
{
    public function handle($request, Closure $next, $guard = null)
    {
        if(Auth::user()->approved != true){
            redirect('/error');
        }
        return $next($request);
    }
}

So far middleware attached here:

Route::get('/home', 'HomeController@index')->middleware('confirmed')->name('home');

However, it does not work. No errors as well.

You're better off checking this when a user logins instead of using a middleware.

Add this to the LoginController and perform any additional checks. This method will be called after the user successfully logs in.

protected function authenticated($request, $user)
{
    if($user->approved != true){
        return redirect('/error');
    }
}

If you still insist on using middleware, then make sure you add the middleware in Kernel.php

Add this in app/Http/Kernel.php

'confirmed' => \App\Http\Middleware\ConfirmedMiddleware::class,

You're also missing the return in your redirect.

public function handle($request, Closure $next, $guard = null)
{
    if(Auth::user()->approved != true){
        return redirect('/error');
    }

    return $next($request);
}

您缺少重定向中的返回,应该是:

return redirect('/error'); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM