Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dmcglone's avatar

restricting access for registered users

Does anyone know of any tutorials or @JeffreyWay's videos that demonstrate restricting access to registered users? For example, what if a user isn't authorized to login until an admin authorizes them?

0 likes
87 replies
mstnorris's avatar
Level 55

@dmcglone Use Middleware.

Copied from a post I answered a couple of days ago.

I have included a basic implementation and requires that you add an admin column to your users table. I'm not suggesting that this is the best way. I personally have set up Users, Roles, and Permissions but the example below will get you started. You can literally swap out admin for verified and you'll be golden!

  1. The following command creates new Middleware called Admin
php artisan make:middleware Admin
  1. This creates a file called Admin.php within the app/Http/Middleware directory that looks like
<?php namespace App\Http\Middleware;

use Closure;

class Admin {

    public function handle($request, Closure $next)
    {

        if ( Auth::check() && Auth::user()->isAdmin() )
        {
            return $next($request);
        }

        return redirect('home');

    }

}
  1. You then need to add the Admin Middleware to your app/Http/Kernel.php file
protected $routeMiddleware = [
    'auth' => 'App\Http\Middleware\Authenticate',
    'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
    'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
    'admin' => 'App\Http\Middleware\Admin', // this line right here
];
  1. Add the Admin Middleware to a route. (Within your routes.php file).
get('protected', ['middleware' => ['auth', 'admin'], function() {
    return "this page requires that you be logged in and an Admin";
}]);
  1. Finally you need to add the isAdmin method we created above to your User model to check whether or not the user is an Admin.
public function isAdmin()
{
    return $this->admin ? true : false; // this looks for an admin column in your users table
}
  1. This will do the trick. If you run into any problems, please post what you have tried and which step you got up to and I'll try my best to help.
5 likes
dmcglone's avatar

I did create some middleware, but I only know how to restrict access to a certain page and not disallow login.

mstnorris's avatar

Just protect the route. You need them to log in to see who they are before you can check with Middleware.

Route::group(['middleware' => ['auth', 'verified']], function()
{
    get('dashboard', ['as' => 'dashboard_path', 'uses' => 'UsersController@dashboard']);

    get('profile', ['as' => 'profile_path', 'uses' => 'UsersController@profile']);

    get('settings', ['as' => 'settings_path', 'uses' => 'UsersController@settings']);
});
toniperic's avatar

Use

Route::group(['middleware' => 'active'], function () {
    Route::get('foo', 'BarController@methodName');
});

And just create the middleware and associate active key to it in Kernel

dmcglone's avatar

I think this is what I wasn't getting right.. Auth::check() && Auth::user()->isAdmin()

Hang on, I'll post my code which is just like @mstnorris's except I wasn't using the line above.

dmcglone's avatar

Ok here's what I created and I see I forgot the route, and the method in my User model.. I was assuming that I could add the restricted code to RedirectIfAuthenticated.

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\RedirectResponse;

class EmployeeAuthentication {

    protected $auth;
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->check())
        {
            if ($this->auth->user()->is_employee == true)
            {
                return $next($request);
            }
        }
        return new RedirectResponse(url('/'));
    }
}

kernel

protected $routeMiddleware = [
        'auth' => 'App\Http\Middleware\Authenticate',
        'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
        'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
        'admin' => 'App\Http\Middleware\AdminAuthentication',
        'employee' => 'App\Http\Middleware\EmployeeAuthentication',
    ];
mstnorris's avatar

Looks good. Just add it to your routes.php.

1 like
martinbean's avatar

As an aside, in the Admin middleware, you don’t actually need to check if the user is authenticated. The Authenticate middleware will check this and redirect if the user is not logged in, thus not reaching the Admin middleware.

dmcglone's avatar

Hmmm, it still allows a user to log in when their is_employee bit is false:

middleware

class EmployeeAuthentication {
    protected $auth;
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }
    public function handle($request, Closure $next)
    {
        if ($this->auth->check())
        {
            if (Auth::check() && Auth::user()->isEmployee())
            {
                return $next($request);
            }
        }
        return new RedirectResponse(url('/'));
    }
}

User model

public function isEmployee()
    {
        return $this->is_employee ? true : false;
    }

Kernel

protected $routeMiddleware = [
        'auth' => 'App\Http\Middleware\Authenticate',
        'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
        'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
        'admin' => 'App\Http\Middleware\AdminAuthentication',
        'employee' => 'App\Http\Middleware\EmployeeAuthentication',
    ];

And finally routes:

Route::get('protected', ['middleware' => ['auth', 'employee'], function() {
    return "this page requires that you be logged in and an employee";
}]);
mstnorris's avatar

@dmcglone do an explicit check

public function isEmployee()
{
    return ($this->is_employee == true) ? true : false;
}

Also, to check, do:

dd(Auth::user()->is_employee);
davorminchorov's avatar

What do you mean by "not using any roles"? According to the code in this thread, you do. Admin and employee are roles. Maybe you don't use them in the way like it is shown in the video.

dmcglone's avatar

@Ruffles, I'm only wanting to learn to restrict access to a user. I've already learned how to restrict a user from pages, now I'm trying to learn how to restrict them from logging in. I've got the concept down, but what I've tried isn't working and that's where @mstnorris is helping me figure out where I'm going wrong.

dmcglone's avatar

Yeah, and dd didn't seem to have an effect, it still logged in and it seems no matter what I try with the route, it still logs in. I even tried a different approach to the route. Seems no matter what I try, it still logs in like I haven't made any changes at all.

So far I changed

Route::get('protected', ['middleware' => ['auth', 'employee'], function() {
    return "this page requires that you be logged in and an employee";
}]);

to this, with no affect.

Route::group([
    'prefix' => '/',
    'namespace' => Auth',
    'middleware' => 'employee'
], function() {
    Route::resource('employee, 'ApplicationController');
});
mstnorris's avatar

@dmcglone You're missing an apostrophe. And of course that won't work.

Use:

Route::get('protected', ['middleware' => ['auth', 'employee'], function() {
   return 'this route is protected, if you can see this then access has been granted';
}]);

If the above doesn't work as expected then something else is going on and I would kindly ask that you paste all your code here exactly as you have it currently and I'll take a look.

dmcglone's avatar

That's weird, it wasn't missing over here. I must've messed up the paste.

dmcglone's avatar

Ok wait a second, I think I found the problem. It may be because I didn't put the ApplicationController in a folder like I did with the AdminController

dmcglone's avatar

Nah never mind, I'm trying to restrict access to Auth, not the application controller.

dmcglone's avatar

@mstnorris Ok this works. I log in the user and if is_employee bit is false, just call /auth/logout. :-)

public function handle($request, Closure $next)
    {
        if ($this->auth->check())
        {
            if ($this->auth->user()->is_employee == true)
            {
                return $next($request);
            }
        }
        return new RedirectResponse(url('/auth/logout'));
    }
dmcglone's avatar

Not sure if it's the correct way to go about it, but I thought about it for a second and realized, I need to be logged in in the first place in order to check to see if they are an employee yet. :-)

Next

Please or to participate in this conversation.