I have two tables :
User ->
id :
name :
role_id : ->refernces('id')->on('roles');
Roles ->
id :
role_name :
access :
I am trying to access roles details from user.
My user model has :
public function role(){
return $this->belongsTo('App\Role');
}
My role model has :
public function user(){
return $this->hasMany('App\User');
}
When I try to do following :
$user = User::find(1);
$details = [
'name' => $user->first_name,
'role' => $user->role->role_name
];
I get error :
Trying to get property of non-object
My roles table contains access columns containing array of permissions to different routes. So my user will have only one role. While a role can have multiple users. How to do that?
In my recent project, I handled these requirement in that way.. First of All Database Table Structure/Migration
User Table
Role Table
Role And User Relation Table
After these table you have to handle permission by assigning to specific Role.
Permission
Permission and Role Table Relation
And Finally our model would look alike:
User Model
Role Model
Permission Model
Well, thats the basic structure helped to implement basic ACL and Auth with laravel 5.
Let me know if you have any further related question. Or If you need complete implementation I'll provide it to you.
For a one-to-many relationship you don't need a pivot table, so you can delete the
user_roles
table. Then add arole_id
column to yourusers
table, that will reference theid
column in for yourroles
table. Next define the relations as follows for each of your models:and
Now you can access your role via the relation like this:
i noticed you are not using the laravel default table naming conventions, you are using user_roles whereass laravel naming conventions state you should use: role_user (alphabetical and singular)
you could override the belongsToMany by stating your custom table name ofcource.
on the second node there are also some good libraries to handle these kind of things, take a look at : https://github.com/romanbican/roles
I got the problem, i was having a role column in user table, so when i was doing
it was fetching
role
column instead of relationship.