ILoveBaymax
ILoveBaymax

Reputation: 267

How to get a value on a pivot table

I am an absolute beginner in Laravel.

I would like to get "role_id" on the pivot table or "admin", but I don't know how. I would like to make a system that shows a different interface based on what role the user has. So I would like to distinguish users from admin, instructor, and user by getting "role_id" on the pivot table.

Any advice would be appreciated.

Users.php

public function users(){
    return $this->belongsToMany('App\User');
}

Roles.php

public function roles(){
    return $this->belongsToMany('App\Role')->withTimestamps();
}

Role table:

1|admin|2016-04-02 16:51:25|2016-04-02 16:51:25
2|instructor|2016-04-02 16:51:25|2016-04-02 16:51:25
3|student|2016-04-02 16:51:25|2016-04-02 16:51:25

I would like to get role_id on the pivot table. I can get the table below with the code "\Auth::User()->roles"

{
"id": "1",
"name": "admin",
"created_at": "2016-04-02 16:51:25",
"updated_at": "2016-04-02 16:51:25",

 "pivot": {
     "user_id": "1",
     "role_id": "1",
     "created_at": "2016-04-02 16:54:06",
     "updated_at": "2016-04-02 16:54:06"
  }

}

Upvotes: 1

Views: 102

Answers (1)

Maytham Fahmi
Maytham Fahmi

Reputation: 33387

I have looked at my roles setup, you need to add the following code after your code in Roles.php

public function hasRole($name)
{
    foreach ($this->roles as $role)
    {
        if ($role->name == $name) return true;
    } 
    return false;
}

public function assignRole($role)
{
    return $this->roles()->attach($role);
}

public function removeRole($role)
{
    return $this->roles()->detach($role);
}

hasRole checks the roles, assignRole and removeRole to add and delete roles.

For testing you can do something like

if ($user->hasRole('student')) return "you are in student group"

Upvotes: 1

Related Questions