Search code examples
laravelrouteslaravel-middleware

Laravel Route->middleware('auth') for different user types


I've been trying to figure out a way to make 3 types of user access to pages:

  1. guest
  2. admin
  3. user

For example:

  • guests should only be able to use the routes /homepage and /login
  • admins should only be able to use the routes /homepage, /logout and /manage
  • users should only be able to use the routes /homepage, /logout and /shopping/cart

Guest is not signed in. Admin and User share some routes, but not all routes should be equal access between the 2

I've been using a workaround in the views to show 3 separate displays:

@auth
    // Paragraph seen by the user with name `admin`
    @if(auth()->user()->attribute == 'admin')
        <p>ADMIN</p>
    // Paragraph seen by every other user
    @else
        <p>USER</p>
    @endif
// Paragraph seen by guests
@else
    <p>GUEST</p>
@endauth

This serves the purpose of hiding things on the page using the attribute value of the user, but I want a way to apply the 3 access tiers on entire routes since regular users can get access to management pages.


Solution

  • you can handle it with guards instead. in config/auth.php define your desired guards like below:

    'guards' => [
        'web' => [
            'driver'   => 'session',
            'provider' => 'users',
        ],
    
        'api' => [
            'driver'   => 'passport',
            'provider' => 'users',
        ],
        'adminapi' => [
            'driver'   => 'passport',
            'provider' => 'admins',
        ],
        'admin' => [
            'driver'   => 'session',
            'provider' => 'admins',
        ],
    ],
    

    the define the providers:

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model'  => Modules\User\Entities\User::class,
        ],
        'admins' => [
            'driver' => 'eloquent',
            'model'  => \Modules\Operator\Entities\Operator::class,
        ],
    
        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],
    

    after that you can use it in your code like this:

    auth()->guard('admin') ? print('admin') : print('user')

    or in your blades with with @auth directive

    you can get more infohere