Support the ongoing development of Laravel.io →
Authorization Blade Middleware

I am working on a blogging application in Laravel 8.

The application gives the users rights by assigning them roles. Every role has a set of permissions. There is a many-to-many relationship between roles and permissions.

In the user-rights view, I output each user's permissions successfully:

 @foreach ($user->role->permissions as $permission)
    <span class="badge bg-primary">{{ $permission->slug }}</span>
 @endforeach

The goal

I am trying to restrict access to the Site settings section of the application, like this:

// Settings routes
Route::group(['prefix' => 'settings', 'middleware' => ['checkUserPermissions:edit-settings']], function() {
	Route::get('/', [SettingsController::class, 'index'])->name('dashboard.settings');
}); 

For this purpose, I have created the checkUserPermissions middleware:

class CheckUserPermissions
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */

    // Permissions checker
    public function hasPermissionTo($permission) {
        return in_array($permission, Auth::user()->role->permissions->toArray());
    }

    public function handle(Request $request, Closure $next, ...$permissions)
    {
      // Check user permissions
        foreach ($permissions as $permission) {
          if (!$this->hasPermissionTo($permission)) { 
            $permission_label = join(' ',  explode('-', $permission));
            return redirect()->back()->with('error', 'You do not have permission to ' . $permission_label);
          }
        }

        return $next($request);
    }
}

The problem

Although the super admin does have the permission to edit settings, dd(in_array($permission, Auth::user()->role->permissions->toArray())) returns false.

That means that the restriction(s) apply when they should not.

Questions

  1. What causes this bug?
  2. What is the easiest fix?
Last updated 2 years ago.
0
Solution

Hi,

The easiest and widely used approach is to use the permission package created by the spatie.be. Laravel-permission.

ajax30 liked this reply

1
Solution selected by @ajax30

@faisal Please have a look at this topic. Thanks!

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Razvan ajax30 Joined 2 Oct 2021

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.