I was starting on learning some Laravel. I am working on a website where you can create an account, which can have roles, and depending on what roles you have, you can do stuff. What it is isn't important, but let me explain the whole situation.
I do have 3 tables:
- One called
users
, which stores information about all users. - One called
roles
, which stores information about all roles (justid
+name
) - One called
user_roles
, which stores which roles users have. It has anid
column (for PK), anuser_id
column (as FK tousers
.id
) and arole_id
column (as FK toroles
.id
)
I do have 2 models:
Model Users:
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'mood'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function roles() {
return $this->belongsTo('App\Role');
}
}
Model Roles:
class Role extends Model
{
protected $table = 'roles';
protected $fillable = ['role'];
}
Now, what I did in one of my controller is add the following line:
var_dump(Auth::user()->roles()->get())
So I got my user, I am logged in, I did add a role and I did add a new user_roles row (with my user ID and the ID of the role I added). However, the var_dump still returns an empty array instead of the role I have. I don't understand what I did wrong