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

mhdd's avatar
Level 9

Check user roles automatic in a middle-ware

Hey guys, (Happy Valentines day :D)

i am watching Jeffrey Way video series about laravel new features on 5.1.*. specially ACL parts.

i follow the videos (ACL With roles & permissions) step by step & of course i made the same sample.

now i want to make some automatic user permission check in middleware or something ... (i dont want to check user's access in every view or controller. )

here is my migrations that i used to make my tabales :

Schema::create('roles', function (Blueprint $table)
        {
            $table->increments('id');
            $table->string('name');
            $table->string('label')->nullable();
            $table->timestamps();
        });

        Schema::create('permissions', function (Blueprint $table)
        {
            $table->increments('id');
            $table->string('name');
            $table->string('label')->nullable();
            $table->timestamps();
        });

        Schema::create('permission_role', function (Blueprint $table)
        {
            $table->integer('permission_id')->unsigned();
            $table->integer('role_id')->unsigned();

            $table->foreign('permission_id')
                ->references('id')
                ->on('permissions')
                ->onDelete('cascade');

            $table->foreign('role_id')
                ->references('id')
                ->on('roles')
                ->onDelete('cascade');

            $table->primary(['permission_id', 'role_id']);
        });

        Schema::create('role_user', function (Blueprint $table)
        {
            $table->integer('role_id')->unsigned();
            $table->integer('user_id')->unsigned();

            $table->foreign('role_id')
                ->references('id')
                ->on('roles')
                ->onDelete('cascade');

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');

            $table->primary(['role_id', 'user_id']);
        });
0 likes
5 replies
mhdd's avatar
Level 9

ok guys i write a middle ware with his code :

class CheckPermissions
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $user = $request->user();
        $segs = $request->segments();

        $perm = explode("\\", $request->route()->getActionName()); // this will return current controller+action. ex: "ForumController@edit"
        return $next($request);
    }
}

and here is my Models :

User :

class User extends Authenticatable
{

    /**
     * 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',
    ];

    public function roles ()
    {
        return $this->belongsToMany(Role::class);
    }

    public function hasRole ($role)
    {
        if(is_string($role))
        {
            return $this->roles->contains('name', $role);
        }

        return !! $role->intersect($this->roles)->count();
    }

    public function assignRole ($role)
    {
        return $this->roles()->save(
            Role::whereName($role)->firstOrFail()
        );
    }

    public function hasPermission ($perm)
    {
    }
}

Role :

class Role extends Model
{
    public function permissions ()
    {
        return $this->belongsToMany(Permission::class);
    }

    public function givePermissionTo (Permission $permission)
    {
        return $this->permissions()->save($permission);
    }
}

Permission :

class Permission extends Model
{
    public function roles ()
    {
        return $this->belongsToMany(Role::class);
    }
}

Now how i can find out that current logged in user in middleware has this specific permission attached to their groups or not. Please help me guys.

thanks.

zachleigh's avatar
Level 47

Just use Gate. I followed the same video and made this middleware:

use Gate;
use Closure;

class RedirectIfNotAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Gate::denies('access_admin_area')) {
            return redirect('/');
        }

        return $next($request);
    }
}
2 likes
mhdd's avatar
Level 9

@zachleigh thanks for your reply. in your example "access_admin_area" should be the name of the permission right? i check it but when i try to access my specific url i get this error :

ErrorException in Gate.php line 321: 

Illegal offset type in isset or empty
mhdd's avatar
Level 9

@zachleigh thank you. it worked like piece of cake. dont know how but it worked. :D

now i have another question. as u watch the video we can access user roles from their model like this :

$user_roles = User::find(1)->roles; // a collection of the roles for user with id 1.

right? now how can i get the reverse of this?

i have a role & i want to get list of users in this role.

$role = Role::find(1); // i want a list of users in this role

i cant get this result in anyway. help me plz

Please or to participate in this conversation.