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

birdietorerik's avatar

Change role on user

Hi!

Developing a webapp/mobileapp Using Laravel 8.x and vue

Using roles for my project.

Need to do this:

Every user have more then 1 role

Example:

Roles for user : xxxxx

Admin Prouser Liteuser Support

After user have logged in, it wil redirect to view that user select wanted role

Admin Prouser Liteuser Support

After he have selected wanted role, the app show the dashboard and menues... But menues are different of every selected role.

My problem is how to change : Auth()->user->roles ???

0 likes
13 replies
koramit's avatar

Maybe after user selected role, you keep the role in session then use session data to filter role.

Auth::user()->roles->where('name', Session::get('selected_role'))

birdietorerik's avatar

Hi!

I get my selected role from my blade form:

public function selectrole(Request $request)
    {
        // Get selected role and startlist 
        $valgtrolle = $request->valgrolle;

        // Set new role
        ???????
        //Auth::user()->roles->where('name', Session::get('selected_role'))

        switch ($valgtrolle) {
            case 1:
                return redirect('admin/dashboard1');
              break;
            case 2:
                return redirect('admin/dashboard2');
              break;
            case 3:
                return redirect('admin/dashboard3');
              break;
            case 4:
                return redirect('admin/dashboard4');
              break;
            case 5:
                return redirect('admin/dashboard5');
              break;
            case 6:
                return redirect('admin/dashboard6');
              break;
            default:
               return redirect('admin/dashboard');
          }
    }

koramit's avatar

From what I understand, User already has many roles then they select what they need to login as right ?

So you keep selected value maybe role id in the session.

Session::put('selected_role', $valgtrolle);

And you can redirect them to what they want using switch.

From now, in any controllers you can get the role user selected using role id you stored in session;=.

$role = Auth::user()->roles->where('id', Session::get('selected_role'));

birdietorerik's avatar

Hi!

Tryed your code Get this error

Error Class 'App\Http\Controllers\Auth\Session' not found

birdietorerik's avatar

Hi!

Fixed the error, but using laravel 8 so i change this code to :

$role = auth()->user()->roles->where('id', Session::get('selected_role'));

But it dosent change the role on the user ?

jlrdw's avatar

Sessions are fine for the web app, but how do you plan to handle the mobile app which is normally token based?

Also I have users with more than one role, but never need to switch. I just check if the method they are performing is one of their assigned roles. But just suggestion.

birdietorerik's avatar

Hi!

My menu shows only items that the role has access to.

On login application use (ROLES)

Role role_user

But in users, no default role ?

I need to change this default value of the role

But how ?

jlrdw's avatar

You could set a default to highest level role. But an example from a real app I had to rework:

  • Bob is an admin

  • Suzy is admin and does bookkeeping

  • Mary is a bookkeeper only

  • If Bob is logged in, Bob can only do admin stuff and all access to user stuff. But Bob cannot mess with bookkeeping.

  • If Suzy is logged in she can access admin stuff and bookkeeping and accounting stuff.

  • If Mary is logged in she cannot mess with admin stuff, but has access to bookkeeping and accounting stuff.

So I just check at method level if the logged in users role can or cannot access that method / function.

And use query scopes to let a user edit / view their own data or an admin can access all users data.

So in pseudocode:

public function some_bookkeeping_function()
    {
        if (a required role of bkeep is not true here) {   // bkeep = bookkeeper
            return redirect('somewhere'); // whereever you redirect to if not authorized
        }
        // Rest of method here is accomplished if 
        // the logged in user has the required role of 'bkeep'.
    }

Again just examples.

Also a Spatie example I saw:

public function update(Request $request, Post $post) {
    if ($post->author !== auth()->user()->id || auth()->user()->cannot('edit posts'))
        abort(404);// or redirect, or whatever action 
    }
    //rest of method if all okay
}

One exception, not shown is if admin wants to only see their data and not all, you could have a toggle (radio). But I just check in the background if the logged in user can or cannot do something.

Just suggestions.

birdietorerik's avatar

Hi!

Thank you for trying t help me with this big problem. Try to anderstand what role laravel use on login, if user have example 3 roles registred to role_user table.

role_table
********

user_id = 2
role_id = 1

user_id = 2
role_id = 4

user_id = 2
role_id = 2

When i login, laravel uses example role_id=1

So if i want role_id=4, i select this from my form. And this part is working fine.

But i must set the default role to role_id=4

Cant figer out how ?

PFrank's avatar

Hi, I am new to this forum. But I have been a regular reader for quite sometime. Noticed this post and thought of joining.

I am having the same issue for sometime. Have tried various methods switching 2 and 3 role_id's but stuck at the same place where @birdietorerik is now.

The only possible way is switching the id's in the session, as you have already passed the middleware. Any suggestion to store this in session ( Session::put ) and regenerate the session? Or to Session::forget the unwanted id's??

Thanks @birdietorerik for bringing this up.

There are many other ways to achieve this before the middleware, then you have to logout and login again.

PFrank's avatar

If you try following you can unset ( Session::forget ) the unwanted id's.

                @php
                    print_r(Session::all());
                    echo ('<br />');
                    Session::forget('role_one');
                    Session::forget('role_two');
                    //Session::regenerate();
                    print_r(Session::all());
                @endphp

The second print_r(Session::all()); shows role_one (role_id 1) & role_two (role_id 2) are removed, only role_three (role_id 4 ) is remaining. But the view is set to the original role_one setting. Have tried Session::regenerate. But no luck.

birdietorerik's avatar

Using this PHP code in my controller -> selectrole


        dd(Session::all());
        
        Session::forget('Admin');
        Session::forget('Superadmin');
        Session::regenerate();
        dd(Session::all());

This is what i get from dd(Session::all()

array:4 [▼
  "_token" => "xZ6u1cFHMIiLBq00pRD2uHAB8pH6XYrGupRwY08D"
  "_flash" => array:2 [▼
    "old" => []
    "new" => []
  ]
  "_previous" => array:1 [▼
    "url" => "http://portal.test:8000/login"
  ]
  "login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d" => 2
]

This is what i get from dd(Session::all()); after

array:4 [▼
  "_token" => "imWonoKaX5J2W2uiT4KDYFnaAauU07Ln1ZMTAuYH"
  "_flash" => array:2 [▼
    "old" => []
    "new" => []
  ]
  "_previous" => array:1 [▼
    "url" => "http://portal.test:8000/login"
  ]
  "login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d" => 2
]

But dosent change anything ???

birdietorerik's avatar

Hi!

When user fill out username and password. And user hit Login-button.

It fires this controller:


<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */

    //protected $redirectTo = RouteServiceProvider::HOME;
    

    public function redirectTo() {

        //$user = User::find(2);
        //$roles = Role::pluck('name','name')->all();
        //$userRole = $user->roles->pluck('name','name')->all();
        
        //dump($userRole);
         return 'roller';
    }
    /**
     * Create a new controller instance.
     */
    public function __construct()
    {
         
        $this->middleware('guest')->except('logout');
    }

    /**
     * The user has logged out of the application.
     *
     * @return mixed
     */
    protected function loggedOut(Request $request)
    {
        if ($request->wantsJson()) {
            return response(null, Response::HTTP_NO_CONTENT);
        }
    }
}

It call this -> use AuthenticatesUsers;

Try to figer out where this AuthenticatesUsers is located in the system.

Cant figer out where in laravel this ->AuthenticatesUsers is ?

Please or to participate in this conversation.