Laravel Authorization
Authorization is a crucial aspect of web applications, ensuring that users only access the parts of an application they are permitted to. Laravel provides a powerful and flexible authorization system using Gates and Policies. This guide will walk you through implementing authorization in Laravel 10/11.
1. What is Authorization in Laravel?
Authorization in Laravel is used to restrict access to resources based on user roles, permissions, or other conditions. Laravel offers two main methods for handling authorization:
- Gates: Simple closures that determine if a user can perform an action.
- Policies: Dedicated classes that group authorization logic for specific models.
2. Using Gates for Authorization
Step 1: Defining a Gate
Gates are typically defined in the App\Providers\AuthServiceProvider.php
file inside the boot
method:
Step 2: Using a Gate in a Controller
You can use the Gate::allows
or Gate::denies
methods in a controller:
Or use authorize
inside a controller method:
Step 3: Using Gates in Blade Templates
3. Using Policies for Authorization
Step 1: Creating a Policy
Policies help organize authorization logic into separate classes. Create a policy for a model using:
This will generate a policy file at app/Policies/PostPolicy.php
.
Step 2: Registering a Policy
In App\Providers\AuthServiceProvider.php
, register the policy:
Step 3: Defining Policy Methods
Modify PostPolicy.php
to define authorization logic:
Step 4: Using Policies in Controllers
Step 5: Using Policies in Blade Templates
4. Role-Based Authorization
To implement role-based authorization, modify your User
model:
Then, use it in controllers or Blade templates:
Blade directive:
5. Middleware for Authorization
Step 1: Creating a Middleware
You can create custom middleware to restrict access based on roles:
Modify app/Http/Middleware/AdminMiddleware.php
:
Step 2: Register Middleware in Kernel
In app/Http/Kernel.php
, add your middleware:
Step 3: Apply Middleware to Routes
In routes/web.php
:
6. API Authorization with Laravel Sanctum
For API authentication, Laravel Sanctum provides a lightweight solution.
Step 1: Install Sanctum
Step 2: Publish the Configuration
Step 3: Protect API Routes
Modify app/Http/Kernel.php
:
Step 4: Assign Tokens to Users
In your controller, grant API tokens:
Step 5: Secure API Routes
In routes/api.php
:
Conclusion
🎉 Congratulations! You now have a solid understanding of Laravel Authorization using Gates, Policies, Middleware, and Laravel Sanctum for APIs.
💬 Have any questions? Let us know in the comments!