0
votes

I have the following in my controller method that returns JSON to my view:

    public function RolesForUser()
    {
        $userid = Input::get('userid');

        $assigned = DB::table('assigned_roles')
                ->select(array('role_id'))
                ->where('user_id', '=', $userid)
                ->get();

        $user = User::find($userid);
        $roles = $user->roles();

        $data = array('assigned' => $assigned, 'roles' => $roles);
        return Response::json($data);
    }

Returns the following (inspected using Fiddler):

{"assigned":[{"role_id":"2"},{"role_id":"3"},{"role_id":"4"}],"roles":{}}

The SQL statement that uses Query Builder returns the correct results, but the method that uses Entrust (copied from Entrust Issue 34, after making the change to my User model) doesn't return any roles.

I also tried the solution in this SO question, but it just gives my an SQL error.

Any ideas where I'm going wrong, I'm on Laravel 4.2.11?

My User model:

class User extends Eloquent implements UserInterface, RemindableInterface 
{
use HasRole;

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'Users';

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
protected $hidden = array('Password');

protected $primaryKey = 'UserID';

public $timestamps = false;

/*Standard methods removed for brevity*/

public function roles()
{
    return $this->hasMany('Role');
}
}
1
Looks like the relationship between the User model and it's roles is setup in a way that is it not working for you. Can you append the used relationship methods or traits? Thanks! - hannesvdvreken
@hannesvdvreken - I've added the relevant bits of my User model - SteB

1 Answers

0
votes

It looks like you have a roles method defined that should not be defined. The use of the Trait HasRole already adds the roles relationship to the User model.

Take a look at the other stuff that the HasRole adds to your model: https://github.com/Zizaco/entrust/blob/master/src/Entrust/HasRole.php

The roles() method returns a relationship. It is recommended to return ->roles or ->roles()->get().

Hope this helps.