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

mehmetanbaki's avatar

Login Roles

Hey Laravelers

I made login with middleware for three roles but instead of Auth::user() I used Auth::role()

and the role is from other table the connection between role and user is pivot table because I make two tables one for users and one for roles but it didn't work.

It giving me this error

BadMethodCallException Method Illuminate\Auth\SessionGuard::role does not exist.

0 likes
31 replies
Nakov's avatar

@mehmetanbaki of course, an Auth is not a user.. you should use Auth::user()->role for example.

mehmetanbaki's avatar

and how can I get the role_name from the other table for roles ??

mehmetanbaki's avatar

this is the code in the login controller :

use AuthenticatesUsers;

/**

  • Where to redirect users after login.
  • @var string */ // protected $redirectTo = RouteServiceProvider::HOME;

protected function redirectTo(){

if (Auth::role()->role_name == 'admin') {
    return route('dashboard');
} elseif (Auth::role()->role_name == 'accountant') {
    return route('main');
} elseif (Auth::role()->role_name == 'customer') {
    return route('index');
} else {
    return redirect('/login')->with('status', 'يرجى إدخال إسم المستخدم وكلمة المرور');
}

}

/**

  • Create a new controller instance.
  • @return void */ public function __construct() { $this->middleware('guest')->except('logout'); }
mehmetanbaki's avatar

it giving me that error:

ErrorException Trying to get property 'role_name' of non-object

Nakov's avatar

@mehmetanbaki Do you have role assigned for each user?

Does your users table have role_id?

In your User model you have:

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

And the role_id cannot be null for the user?

mehmetanbaki's avatar

look the tables is just like that

  1. users
  2. roles

and third table as pivot it's called :

user_role

the pivot table connect them with there id as user and role

Nakov's avatar

@mehmetanbaki so one user can have many roles?

Can you show me the User model, and how you've setup the relationship.. or use the questions that I am asking to ask yourself, and understand why this is failing.. Because the way you've setup the relationships now, a User can have many roles, so you cannot just check if a User is an admin, but if he contains that role in a collection of roles.

mehmetanbaki's avatar
namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

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

    public function ffprints(){
        return $this->belognsTo(User::class);
    }
    public function employee(){
        return $this->hasMany(Employee::class);
    }

    public function corporation(){
        return $this->hasMany(Corporation::class);
    }

    public function bank(){
        return $this->hasMany(Bank::class);
    }

    public function salary(){
        return $this->hasMany(Salary::class);
    }
}

mehmetanbaki's avatar
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('username');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}
mehmetanbaki's avatar
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateRolesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('user_id');
            $table->foreign ('user_id')->references ('id')->on('users');
            $table->string('role_name');
            $table->string('role_level');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('roles');
    }
}
Nakov's avatar

@mehmetanbaki you've been using Laracasts for a while now, you should know that sharing code using ``` from each side of the code is what makes the code to look proper now. So please edit your replies. And you can also use one reply instead of 3 separate..

So as I said, I will say it again:

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

This won't work, as you have MANY to MANY relationship, not the way I thought you had.

https://laravel.com/docs/master/eloquent-relationships#updating-many-to-many-relationships

mehmetanbaki's avatar

I changed it to hastMany and it's the same

it's giving me this error


Property [role_name] does not exist on this collection instance. 

mehmetanbaki's avatar

and again try this

belongsToMany and didn't work give me that error


Illuminate\Database\QueryException
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'simpay.role_user' doesn't exist (SQL: select `roles`.*, `role_user`.`user_id` as `pivot_user_id`, `role_user`.`role_id` as `pivot_role_id` from `roles` inner join `role_user` on `roles`.`id` = `role_user`.`role_id` where `role_user`.`user_id` = 1)


Nakov's avatar

Your relationship should be

public function roles()
{
    return $this->belongsToMany(Role::class, 'user_role');
}

And then use this:

if ( Auth::user()->roles->contains('role_name', 'admin') )
mehmetanbaki's avatar
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'simpay.role_name' doesn't exist (SQL: select `roles`.*, `role_name`.`user_id` as `pivot_user_id`, `role_name`.`role_id` as `pivot_role_id` from `roles` inner join `role_name` on `roles`.`id` = `role_name`.`role_id` where `role_name`.`user_id` = 1) 


This what happen

mehmetanbaki's avatar

you mean I have make pivot table and put the id's for the users table and roles table in it ???

Nakov's avatar

@mehmetanbaki yes, it means that you don't have a migration that creates the pivot table. So in your database that table does not exists at all :)

mehmetanbaki's avatar

but I put the user_id in the roles table why it doesn't work ???

Nakov's avatar

OMG, you have no clue what you are doing. There is the documentation, there are MANY, MANY videos on Laracasts, 1601 until today. So go ahead and watch some. I am no longer responding to you.

Sorry, had to respond this way. It will take forever for me to teach you this way.

mehmetanbaki's avatar

I fixed it and it work fine just put this :

' ' '

public function users() {
    return $this->belongsToMany(User::class);
}

' ' '

in the Role Model

Nakov's avatar

@mehmetanbaki really was that all that you needed to do :) or you needed to create the role_user table in order to work :)

I understand the errors very well my friend :)

mehmetanbaki's avatar

no no you're totally right but I add that to the role model to make it work besides your advice

Next

Please or to participate in this conversation.