Ad

Multi User Role In Laravel 8

- 1 answer

I want to redirect to the user's dashboard according to role. I have created a separate table for the user role and a separate table for the user. I don't understand how I can do that.

This is my middleware code

public function handle(Request $request, Closure $next)
    {
        if(!Auth::check()){
            return redirect()->route('login.user')->with('error', 'Please login first');
        }

        if(Auth::user()->role == 1){
            return $next($request);
        }

        if(Auth::user()->role == 2){
            return redirect()->route('user.dashboard');
        }
    }

This is my user role table

iduser_type
1admin
2user

This is my user table

iduser_nameuser_role_id
1admin1
2user2

I would be very happy if you could help me.

Ad

Answer

In the User Model you have to define the role relationship.

Put this to your User Model:

    public function role()
    {
       return $this->belongsTo(Role::class, 'user_role_id');
    }

Of course you have to have the Role model, but I guess you already have that

public function handle(Request $request, Closure $next)
    {
        if(!Auth::check()){
            return redirect()->route('login.user')->with('error', 'Please login first');
        }

        if(Auth::user()->role->user_type == 'admin'){
            return $next($request);
        }

        if(Auth::user()->role->user_type == 'user'){
            return redirect()->route('user.dashboard');
        }
    }

Another solution could be without relationship just like this:

public function handle(Request $request, Closure $next)
    {
        if(!Auth::check()){
            return redirect()->route('login.user')->with('error', 'Please login first');
        }

        if(Auth::user()->user_role_id == 1){
            return $next($request);
        }

        if(Auth::user()->user_role_id == 2){
            return redirect()->route('user.dashboard');
        }
    }
Ad
source: stackoverflow.com
Ad