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

younus's avatar

Best practice for user roles

Assuming I have an Users table which has the following fields

  1. ID
  2. Name
  3. Email
  4. Role (0-admin, 1 user)
  5. Timestamps

I have an Admin Middleware which Accepts/Rejects requests to Routes by checking the Role of the user. And I use Laravel's default Auth package to handle authentication.

Is this approach better when compared to having two separate tables? If admin part of the website shares sessions with the user part, if an authenticated normal user tries to access the admin panel, he may get the right to access if there's an admin whose id is the same as this normal user. What is the best approach in developing a Laravel 5.1 application where there are multiple user roles, which each user having independent operations.

0 likes
3 replies
Hamelraj's avatar

im not clear about you requirement but i hope this will help you if you have a user_id in your second table in your view or controller you can use

controller - if($object->user_id == Auth::id()){}
View - if($object->user_id == user()->id){}
younus's avatar

This approach would fail when you have a huge application, and code maintenance would become a mess. I want to know what is the best way to have multiple use roles, each with separate controllers/views and develop maintainable code.

Hamelraj's avatar

Then you create middle ware like this use your controller

public function handle($request, Closure $next)
    {
        if($this->admin->user()->role = '1')
        {
            \Session::flash('flash_message','You don\'t have the permission to operate this record! Only Aadmin can operate records.');

            return Redirect::back();
        }
        return $next($request);
    }

i hope you know how to register middle ware to your kernel then you can use your middleware your cotroller any function like this

public function __construct()
    {
        $this->middleware('auth');
     $this->middleware('admin', ['only' => 'yourfunction']);
    }

or you can use grup middleware check this https://laracasts.com/discuss/channels/general-discussion/multiple-middleware-on-routing-group?page=1

Please or to participate in this conversation.