I have a users, roles and role_users table. In the roles table I have a user and admin value. Now I want to be able to edit users when the role of a user is admin. I don't know how to access the role_name == 'admin' in laravel.
When I use this it works :
@if(Auth::user()->user_username == 'Gilko')
But I want to be able to access this role_name == 'admin'
role_users migration
public function up()
{
Schema::create('role_users', function($table)
{
$table->increments('role_user_id');
$table->integer('role_id')->unsigned();
$table->integer('user_id')->unsigned();
});
Schema::table('role_users', function($table)
{
$table->foreign('role_id')
->references('role_id')->on('roles');
//->onDelete('cascade');
$table->foreign('user_id')
->references('user_id')->on('users');
//->onDelete('cascade');
});
}
User model :
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'users';
protected $primaryKey = 'user_id';
protected $hidden = ["password"];
public function getAuthIdentifier()
{
return $this->getKey();
}
public function getAuthPassword()
{
return $this->user_password;
}
public function getReminderEmail()
{
return $this->email;
}
public function user()
{
return $this->hasMany('Checklist', 'user_id', 'user_id');
}
public function roles(){
return $this->belongsToMany('Role', 'role_users', 'user_id', 'role_id');
}
public function getRememberToken()
{
//return $this->remember_token;
}
public function setRememberToken($value)
{
//$this->remember_token = $value;
}
public function getRememberTokenName()
{
//return 'remember_token';
}
}
You can add a function which checks for this on your user model...
public function isAdmin()
{
return (bool)$this->roles()->where('name', 'admin')->count();
}
And then you can easily use it with...
@if(Auth::user()->isAdmin())
You should be able to do something like this:
if (Auth::user()->roles()->where('name', 'admin')->first())
first
will return null if there's no result.
You can also use firstOrFail
: http://laravel.com/docs/eloquent
try (Auth::user()->roles()->where('name', 'admin')->firstOrFail()) {
// User has admin role
} catch (ModelNotFoundException $e) {
// User doesn't have admin role
}
Edit Just realized I had a brain fart. Corrected the code :-)