Search code examples
laravellaravel-5.3

How to get data from other table with Auth::user()->id


I have two tables: Role and User

User

id
name
email
password
Roleid

Role

id 
name

I want is to get name of Role for current logged in User. Something like Auth::user()->role()->name;


Solution

  • Based on you define correct relation between roles and users table you should doing something like this:

    $user = auth()->user();
    $role = $user->role->name // Name of relation function in user model and gather all role data
    

    if you dont define correct relation between users and roles you must do something like this:

    in users table define a column named: role_id

    and in users model doing:

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

    and in roles model :

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