No. A simple "role" column in your user table would be sufficient.
A pivot table is for a many-to-many relationship. So a user could have many roles, a role can belong to many users. Not the case for your app.
So you are suggesting just a role_id in the users? Reason I'm asking about this is because if I get all the users it would obviously return all the integer values from that field but instead would want it to get the name of the actual role which is contained in the roles table with an id and name fields.
//role model
public function users()
{
return $this->hasMany('User'); // this will get all the users that have a role_id that matches it's own id
}
//user model
public function role()
{
return $this->belongsTo('Role'); // this will select the role by 'role_id' and return an instance
}
//controller
echo Auth::user()->role->name; // this will get the name of the role with an id of 'role_id'
$users = Role::with('users')->find(1)->users; // this will get all the users with the specified role id of 1
That takes care of the models but what about the database?
CleverCookie said:
//role model public function users() { return $this->hasMany('User'); // this will get all the users that have a role_id that matches it's own id } //user model public function role() { return $this->belongsTo('Role'); // this will select the role by 'role_id' and return an instance } //controller echo Auth::user()->role->name; // this will get the name of the role with an id of 'role_id' $users = Role::with('users')->find(1)->users; // this will get all the users with the specified role id of 1
It would be just like you said -- a role_id column in your Users table, that would map to the appropriate row in the Roles table.
Is this correct for best practices for storing this data in a database? Also if I'm getting all users and want to attach the name of the role for each user how would I echo out that value so that in the users array it would show up as such.
array(1) {
[0]=>
array(3) {
["username"]=>
string(6) "User 1"
["email"]=>
string(17) "[email protected]"
[0]=>
array(2) {
["role_id"]=>
int(1)
["role_name"]=>
string(4) "User"
}
}
}
Or something to that extent.
all you need is a role_id on your users table. Then just do the echo I previously posted
$users = User::all();
foreach($users as $user)
{
echo $user->role->name;
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community