I am using laravel to create a website for my youth movement. I currently have three tables set up for my roles: Users
, Roles
and role_user
. They look as following:
+-------+ +-------+ +-----------+
| Users | | Roles | | role_user |
+-------+ +-------+ +-----------+
| id | | Id | | user_id |
| Name | | Name | | role_id |
+-------+ +-------+ | start |
| stop |
+-----------+
The user_role
table is a pivot table between users
and roles
. A user can be in a certain role for a certain time defined from role_user.start
until role_user.stop
.
I am trying to create a function in my User
model to check if a user is an admin, this is either a user role 1 or 2, but a user can have more roles as well. I have already tried different ways of achieving this, but it is getting way to complicated and it never works.
The relationships have been made correctly, I am sure of this because I use them in other functions as well.
For example:
User.php:
/**
* Find the roles for this user.
*/
public function user_roles()
{
return $this->belongsToMany('Role')->withPivot('start', 'stop');
}
Can anyone help me with this?
Thanks in advance, Jerodev
Assuming you always want all roles between start
and stop
, you can add a few where()
's to your relationship.
public function user_roles()
{
$now = \Carbon\Carbon::now();
return $this->belongsToMany('Role')->withPivot('start', 'stop')->where('start', '<', $now)->where('stop', '>', $now);
}
Additionally, you can do a lot more with Carbon
's methods:
\Carbon\Carbon::now()->subDays(2);
Depending on you're format of timestamp in start
and stop
, you may need to format $now
properly.
Given the tables you pasted, your relationship is not correct. It lacks table name (Eloquent looks for role_user
by default).
So either this is the name of that pivot table, or it does not work, and you should have:
public function user_roles()
{
return $this->belongsToMany('Role', 'user_role');
}
Anyway, to get your admins:
public function adminRoles()
{
$now = \Carbon\Carbon::now();
return $this->belongsToMany('Role')
->wherePivot('start', '>=', $now)
->wherePivot('stop', '<=', $now)
->wherePivot(function ($q) {
$q->whereIn('role_id', [1,2]);
})
->withPivot('start', 'stop');
}
You can alternatively use CURRENT_TIMESTAMP
instead of Carbon.
Of course this is not the best solution, since roles are hard-coded. So adjust it to meet your needs.
Then to select admin users:
User::has('adminRoles')->get();