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.
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
- How do you validate requests in Laravel? Why use Form Requests?
- How do queues work in Laravel?
- What is mass assignment, and how do $fillable and $guarded protect against it?
- How do database transactions work in Laravel, and what pitfalls should you know?
- Which Artisan commands would you run when deploying Laravel to production, and why?
- What is the service container, and how does dependency injection work in Laravel?
- What is the N+1 query problem in Eloquent and how do you prevent it?
- A Laravel endpoint is slow. How do you find and fix the cause?