skip to Main Content

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.

2

Answers


  1. 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'  => ModulesUserEntitiesUser::class,
        ],
        'admins' => [
            'driver' => 'eloquent',
            'model'  => ModulesOperatorEntitiesOperator::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

    Login or Signup to reply.
  2. Youre after something like this

    @if(Auth::guard('admin')->check())
     Admin
    @elseif(Auth::guard('user')->check())
    User
    @else
         @guest()
        Guest
         @endguest
    @endif
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search