Laravel interview question · Most asked

Gates or policies: how does authorization work in Laravel?

Summary

Gates are closures for actions not tied to a model (viewAdminDashboard); policies are classes that group authorization for one model (OrderPolicy::update($user, $order)). Both are checked with can, authorize, @can or the can middleware.

Longer Answer

Policies are auto-discovered by naming convention (App\Policies\OrderPolicy for App\Models\Order). Methods map to actions: viewAny, view, create, update, delete, restore, forceDelete. In a controller, $this->authorize('update', $order) or Gate::authorize(...) throws a 403 when denied.

before() on a policy (or Gate::before) can grant super-admins everything; return null to fall through. Responses can carry a message (Response::deny('...')) or hide existence with denyAsNotFound().

The common failure is forgetting the check on one endpoint, especially APIs with route-model binding. Authorize in every controller action (or via authorizeResource/middleware), and write tests that call endpoints as another user.

Key Points

  • Gates: closures; policies: per-model classes.
  • authorize() throws 403.
  • before() for super-admin bypass.
  • Test that other users get 403/404.

Deep dive: Code Clinic: review a Laravel orders controller

Explanation

What interviewers look for

The candidate treats authorization as something to enforce on every endpoint and test, not just define.

Follow-up questions

  • How do you return 404 instead of 403 to avoid leaking existence?

More most-asked Laravel questions

← All Laravel questions