Jerodev
Jerodev

Reputation: 33186

Get users with current role

I am using Laravel to create a website and I have a problem with eloquent. I have a database scheme as following:

*****************           *****************
*   Users       *           *   User_roles  *
*****************           *****************
*   id          *I----+     *   id          *
*   name        *     +----K*   user_id     *
*   password    *           *   role_id     *
*****************           *   start_date  *
                            *   stop_date   *
                            *****************

All neede relationships have been made in the models, there is a one to many from the users to the roles, a user can have multiple roles at the same time.

I was wondering if someone can help me to get all users which are in role_id 3 on the current date using eloquent. I can't seem to be able to use the relationship or create a join.

Update: I have now created the relationships between the tables and I am starting from the user_roles table.

This is the code in my models:

// User.php
public function user_roles()
{
    return $this->hasMany('UserRole', 'user_id');   
}

// UserRole.php
public function user() 
{
    return $this->belongsTo('User', 'user_id');
}

I was wondering how I can now filter the users when I start from the User_roles table.

Upvotes: 0

Views: 152

Answers (1)

Donny van V
Donny van V

Reputation: 961

Try using Zizaco Confide and Entrust, i love them :) 2 packages that are easy to install and use.

if im right for your current code:

//Class roles
public function getUsers(){
    return $this->hasMany('User');
}


//In the controller:
$role = Role::find(role_id_here);

foreach($role->getUsers AS $user){
    echo $user.'<br />';
}

Upvotes: 1

Related Questions