Benua
Benua

Reputation: 269

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.

Upvotes: 0

Views: 422

Answers (2)

Sandeesh
Sandeesh

Reputation: 11916

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);
}

Upvotes: 3

Alan Torres
Alan Torres

Reputation: 125

You are missing the return in the redirect, It should be:

return redirect('/error'); 

Upvotes: 1

Related Questions