How to check if user has permission to access this function in Laravel

How to check if user has permission to access this function in Laravel

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

How to check if user has permission to access this function in Laravel

Repeating an Auth::user()->hasPermissionTo() check at the top of every controller method is inefficient and cluttered. It couples your business logic tightly with authorization checks, making the code harder to read and maintain. The goal is to separate the what (the action) from the who (the permission requirement).

The issue in your helper function stems from how you are invoking it. In your index method, you call userHasPermission('users show active'), but you do not use its return value or handle its output correctly. However, there is a more fundamental architectural problem: mixing API response generation inside a permission check helper pollutes the controller flow and breaks separation of concerns.

Why your helper function isn't working

The primary reason your helper fails to stop execution is likely related to how Laravel handles truthy/falsy values and exceptions versus return values.

In your index method, you call the function but ignore the result:

userHasPermission('users show active');
// Execution continues here regardless of whether the function returned a Response object or null
$getUsers = $this->users->getAllActive();
return Response::json($getUsers);

Even if your helper function returns a Response object when permission is denied, simply calling it does not automatically stop execution or prevent subsequent code from running. You must explicitly check the return value or, better yet, leverage Laravel's exception handling mechanism.

Furthermore, checking against a generic 'do everything' permission alongside specific permissions introduces complexity in your permission definition system. If a user has 'show all users', they likely should have access to that specific action. Relying on a blanket "do everything" flag often indicates a permission structure that needs refinement rather than just adding a check.

The Exception-Based Approach

The standard, idiomatic way to handle this in Laravel is to let the request fail fast by throwing an exception. This allows you to write clean helper methods (or traits) that throw exceptions when access is denied, while keeping your controllers focused on processing data.

Create a helper method or use a trait that validates permissions and throws an AuthorizationException if the user lacks rights:

if (!function_exists('checkPermission')) {
    function checkPermission($permission)
    {
        $user = Auth::user();

        // Ensure user is logged in first
        if (!$user) {
            throw new \Illuminate\Auth\AuthenticationException;
        }

        if (!$user->hasPermissionTo($permission)) {
            throw new \Illuminate\Auth\AuthorizationException(403);
        }
    }
}

Update your controller method to call this helper and let the exception propagate:

public function index()
{
    checkPermission('show all users'); // Throws if denied
    
    $getUsers = $this->users->getAllActive();
    
    return response()->json($getUsers);
}

When AuthorizationException is thrown, Laravel's global exception handler (or middleware) can catch it and transform it into your specific JSON error response defined in api_responses. This keeps your controllers clean without needing to manually instantiate Response::json inside every permission check.

Using Gates for Complex Logic

If you find yourself checking permissions repeatedly for the same resource, consider using Laravel's Gates. Gates provide a declarative way to define authorization rules that can be reused anywhere in your application.

Define a gate in your app:

// In AppServiceProvider or Console Kernel
Gate::define('show users', function (User $user) {
    return $user->hasPermissionTo('show all users');
});

Then apply it to your controller method using the authorize method:

public function index()
{
    // This implicitly checks 'show users' gate defined above
    $this->authorize('show users'); 

    $getUsers = $this->users->getAllActive();
    
    return response()->json($getUsers);
}

This approach is cleaner than passing string permissions around, especially if your permission strings are dynamic or complex. It also allows you to define custom logic (e.g., checking if the user owns the resource) within the gate closure rather than just checking a boolean flag.

Middleware as an Alternative

For API routes where you need to protect entire endpoint groups, middleware is often more efficient than repeating checks in every controller. You can create a custom middleware that validates permissions for a specific route or group:

// app/Http/Middleware/CheckPermission.php
public function handle($request, Closure $next, $permission)
{
    if (!Auth::user()->hasPermissionTo($permission)) {
        return response()->json([
            'message' => trans('api_responses.authorization_failed'),
            'code'    => 403,
        ], 403);
    }

    return $next($request);
}

Register this middleware in your route groups:

// RouteServiceProvider
$router->group([
    'middleware' => ['api', 'auth:sanctum', \App\Http\Middleware\CheckPermission::class]
], function ($router) {
    $router->get('/users', [UserController::class, 'index']);
});

This ensures that every request to /users passes the permission check before reaching the controller logic, reducing code duplication and ensuring consistent error responses.

Conclusion

To avoid repeating permission checks in every function, stop returning Response objects from helpers and instead throw exceptions or use Gates/Middleware. Throwing an AuthorizationException is the most robust solution because it aligns with Laravel's exception handling pipeline, allowing your global exception handler to convert it into the desired JSON response automatically. This keeps your controllers readable and your authorization logic centralized.

Our network