$users = User::with(['roles' => function($q){
$q->where('name', 'admin');
}])->get();
How do I get all Users with Roles where role = 'admin' using eloquent along with Entrust?
I've been using RAW queries but now want to do the right way.Hope you guys will help me!
Role Model
namespace App\Models;
use Zizaco\Entrust\EntrustRole;
use Illuminate\Database\Eloquent\Model;
class Role extends EntrustRole
{
}
User Model
namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Zizaco\Entrust\Traits\EntrustUserTrait;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use EntrustUserTrait;
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['password'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
public function roles()
{
return $this->belongsToMany('App\Models\Role');
}
}
I want to get all the users with their roles like this
name | role
Ryan | admin
Megan | admin
I tried this but doesn't work
$users = User::with('roles')->where('roles.name','=','admin')->get();
Error
Column not found: 1054 Unknown column 'roles.name' in 'where clause' (SQL: select * from users where roles.name = admin)
@ashwebb many cases where a user can have multiple roles. Example is forums where a user has a primary role that has basic permissions and a display roll with specific permissions for a particular forum.
Answer to @laraDev98. Run the inverse of the query. Role::with('users')->where('name', 'admin')->get();
Please or to participate in this conversation.