Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Philipp's avatar

Check if user has Admin role

Hi all,

so i've set up my DB's for roles and user_role and with php artisan tinker i could already establish the connection.

Now in my user model i want to add the function isAdmin but i need some help as to how i need to write this.

public function isAdmin() {

    return $this->hasRole('Admin'); // ?? something like this! should return true or false
}

The if i get this working i should be able to use this in my templates:

@if ( $user->isAdmin() )
    <p>Yay! I'm Admin! :P</p>
@endif

Next step then would be to create a middleware to protect certain controller methods. Might come back again when i'm that far.

I've already put up some threads and every time i got good help in a matter of minutes! Big thank you to all out there!

0 likes
28 replies
romanbican's avatar

I think that the best way how solve roles and possibly permissions is to use a package. For example look at mine - https://github.com/romanbican/roles

If you don't want to use this package, have a look at code (src/Bican/Roles/HasRole.php) and I think you will find an answer to your question.

Philipp's avatar

Thanks @romanbican !

I really want to do this whole thing myself before i consider using a package. Otherwise i'll never get on top of it.

So i haven't been this far of - "hasRole" is part of L5 already then? I need to get the name of the Role although, which in this case is "Admin"

public function isAdmin() {

    return $this->hasRole->name('Admin');
}
2 likes
Philipp's avatar

Nah this doesn't work either... is there something i can use to check if the User has the Admin role?

Sorry. :(

usman's avatar

Can we see your code for Role and User models?

romanbican's avatar
Level 9

Well no, it's more complicated. First of all, you need to set up roles method to get all roles that belongs to a user. Inside you User model add this:

    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }

It means you need to also create Role model.

Then you can add this to User model:

    public function isAdmin()
    {
        foreach ($this->roles()->get() as $role)
        {
            if ($role->name == 'Admin')
            {
                return true;
            }
        }

        return false;
    }

It's just an example, but it should work. But it is not ideal.

This is better:

    public function is($roleName)
    {
        foreach ($this->roles()->get() as $role)
        {
            if ($role->name == $roleName)
            {
                return true;
            }
        }

        return false;
    }
8 likes
Philipp's avatar

Role.php

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model {

    protected $fillable = [
        'name'
    ];

    /**
     * A role can have many users.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function users() {

        return $this->belongsToMany('App\User');
    }

}

User.php

<?php namespace App;

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;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

    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 = ['name', 'email', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    /**
     * A user can have many articles.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function articles() {

        return $this->hasMany('App\Article');
    }

    /**
     * A user can have many roles.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function roles() {

        return $this->belongsToMany('App\Role')->withTimestamps();
    }

    /**
     * Check if user has admin role.
     *
     * @return mixed
     */
    public function isAdmin() {

        return ??; //what i am looking for!
    }

}
Philipp's avatar

Oh nice!!! Man you guys are awesome! Thanks again for the help!

I will make sure to test out your package @romanbican !

toniperic's avatar

@romanbican I really like your roles-package. Is there a way to use middlewares to respond to requests?

For instance - if user isn't of specific role OR doesn't have permission - do something in the middleware, so our controllers can stay "cleaner"?

romanbican's avatar

@tonicperic Well, you can create your own middlewares of course and then check if the user is for example admin. It is easy.

This should work:

    public function handle($request, Closure $next)
    {
        if ( ! $this->auth->user()->isAdmin())
        {
            return new RedirectResponse(url('/home'));
        }

        return $next($request);
    }
toniperic's avatar

@romanbican sure. What if I had really lots of roles, or really really big number of permissions? I would have to create a middleware for every permission?

anouarabsslm's avatar

@toniperic inject your ACL to the midleware . for example lets say within your ACL you check if user is admin

<?php namespace App\Http\Middleware;

use Closure;
use Path\T\Your\ACL;
use Illuminate\Http\RedirectResponse;
use Illuminate\Contracts\Routing\Middleware;

class DashBoard implements Middleware {

    /**
     * The Acl implementation.
     *
     * @var Acl
     */
    protected $acl;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     * @return void
     */
    public function __construct(ACL $acl)
    {
        $this->acl = $acl;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->acl->is_admin())
        {
            return new RedirectResponse(url('/dashboard'));
        }

        return $next($request);
    }

}
romanbican's avatar

I think you don't need to create middleware for every permission. For every role, yes, i think that's the best solution. But for example when you are submitting form, you can check if user has permission inside your FormRequest, where is a method authorize.

And is it really bad to check for permissions inside controllers?

jekinney's avatar

You could use one middleware that excepts a variable like permissions name.

And is something bad? Only if it doesn't work. But where you put stuff always depends.. (hate that depends word too). Generally I try to dry my code so if I am repeatedly doing the exact same thing (copy and paste) you probably could extract it to one method or function and just call it. This may seem not to dry, but if used right a lot more readable depending on your naming conventions.

jesseleite's avatar

I'm trying to do the same thing. I set an Auth::user()->is('admin') check, which I already have working (returns true or false as expected).

My problem now is, I also have a ServiceOrder Eloquent model with a foreign key relation to User's ID. Whenever any of my controllers call ServiceOrder::get(), I want only return the ServiceOrders that belong to that User, unless User is an admin, in which case display all ServiceOrders.

I know I can setup a query scope method in my model, and just call ServiceOrder::user($id)->get()... however, I'd rather be able to call ServiceOrder::get() safely anywhere, and have a middleware check for admin permissions and automagically apply query scope when necessary. Is this possible using middleware?

aleksov's avatar

I create my own code:

public function index() {

    $checkAuth = \Auth::user()->admin;

    if ($checkAuth == 1) {

        $articles = Auth::user()->articles()->latest()->get();

        return view('articles.index', compact('articles'));
    }
    return 'You are not ADMIN';

}

Works fine but - > What is wrong with this code?

Firemaps's avatar

Role.php

class Role extends Model
{
    // fields that are available for us to use
    protected $fillable = ['name'];
}

User.php

    /*
    * The user belongs to a role (specified in db)
    */
    public function role() {
        return $this->belongsTo('App\Role');
    }

    /*
    * Function to check if the user is admin
    */
    public function isAdmin() {
        if($this->role->name == 'Administrator') {
            return true;
        }
        return false;
    }

Roles table

class CreateRolesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('roles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('roles');
    }

Middleware

use Closure;
use Illuminate\Support\Facades\Auth;

class IsAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user = Auth::user();
        if(!$user->isAdmin()) {
            return redirect('/'); //or via ->intended('/destination')
        }
        // else            
        return $next($request);        
    }
}
1 like
micka1066's avatar
if(!Auth::user()->hasRole('admin'))
{
     throw new AuthorizationException("You cannot access this method");
} 
Tyrrx's avatar

By far the best Solution:

protected $fillable = [
    'name', 'email', 'password',
];

protected $hidden = [
    'password', 'remember_token',
];

public function roles() {
        return $this->belongsToMany(Role::class, 'users_roles', 'user_id','role_id');
    }

public function isAdmin() {
        return $this->roles()->filter(function (Role $role) {
                   return $role->name == 'admin';
             })->count();
 }

Migration:

public function up() { Schema::create('users_roles', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users');

        $table->integer('role_id')->unsigned();
        $table->foreign('role_id')->references('id')->on('roles');
        $table->timestamps();
    });
}

public function down()
{
    Schema::dropIfExists('users_roles');
}
zerom1nd's avatar

firemaps, Hello, use laravel 5.5 write error:

"Call to a member function isAdmin() on null"

if(!$user->isAdmin()) {

sutherland's avatar

@zerom1nd you must have a null user object then. This is expected when a user isn't logged in. With 5.5 you can use the optional() helper like so:

if(!optional($user)->isAdmin()) {
zerom1nd's avatar

@sutherland if(!optional($user)->isAdmin()) { its work

now log in and error

public function isAdmin() { if($this->role->name == 'Administrator') {

"Trying to get property of non-object"

in database name = "Administrator"

sutherland's avatar

If role is optional you need to do the same thing: optional($this->role)->name

Please or to participate in this conversation.