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

alexm's avatar

[auth] login by role

how works middleware auth to check role of a user to access? can some kind person make me an example? i want not only check if user is registered but also that he belongs to a speciic role (admin, editors ecc) my problem is i would like to have separate login controllers one only login admins one only login editors, so i was thinking about making different users tables. then reading auth documentation i found "middleware"...i got confused there... :) could it be used to route by a role or only if one is logged or not? make different users tables or adding a role value to a single user table? i'm stuck into this decision now... so many paths it is easy get lost :)

0 likes
8 replies
mstnorris's avatar
Level 55

@alexm You wouldn't want to separate the auth into different tables as you'd be duplicating almost all of the code. Your best bet is as you mention Middleware.

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.

  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.
4 likes
pmall's avatar

You can also put middleware in a route group so all admin routes go under this group, all editor routes go in the editor group etc

2 likes
mstnorris's avatar

Of course, but I thought this would give them a start. I didn't want to go too far, otherwise I'd be writing the app for them.

1 like
anon12822's avatar

@mstnorris Very concise!

@alexm I'd also recommend using middleware parameters ( http://laravel.com/docs/master/middleware#middleware-parameters ), this is what I use.

<?php
namespace App\Http\Middleware;

use App;
use Closure;

class CanAccess
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $permission)
    {
        if (!$request->user()->hasAccess($permission)) {
            return App::abort(403);
        }

        return $next($request);
    }

}

And I reference it in my controller __construct() function

    public function __construct()
    {
        $this->middleware('access:users.read');
        $this->middleware('access:users.create', ['only' => ['create', 'store']]);
        $this->middleware('access:users.update', ['only' => ['edit', 'update']]);
        $this->middleware('access:users.restore', ['only' => ['restore']]);
        $this->middleware('access:users.delete', ['only' => ['destroy']]);
    }
alexm's avatar

i want to thank you for the answers, i found them very "illuminating", i'm deeping into middleware docs now it's really "powerful" concept, i see that this could be very handy for my little app !!! mstnorris: "Of course, but I thought this would give them a start." --> yes that was really helpful for people like me starting from zero. you are a very nice community, thank you all again.

1 like
mstnorris's avatar

@alexm you're very welcome. I'm happy you found it useful. I've recently written some Guidelines for posting on Laracasts, please check them out for future reference.

As I say with everything, if you get stuck, don't hesitate to give me a shout and I'll try my best to help where I can.

yassin98010's avatar

I have this error ! FatalErrorException in Admin.php line 16: Class 'App\Http\Middleware\Auth' not found

Please or to participate in this conversation.