Introduction
Laravel provides robust tools for implementing both authentication (verifying user identity) and authorization (determining access rights). With features like Laravel Breeze, Sanctum, and built-in policies/gates, securing your application becomes seamless and efficient.
In this article, we’ll walk through how to implement both authentication and authorization in a Laravel application — with best practices and code examples for real-world usage.
🔐 What’s the Difference?
- Authentication: Confirms a user’s identity (login, registration, sessions).
- Authorization: Determines what authenticated users can do (roles, permissions, policies).
1. Installing Laravel Breeze for Authentication
✅ Install Laravel Breeze (simple auth starter):
composer require laravel/breeze --dev
php artisan breeze:install
npm install && npm run dev
php artisan migrate
This sets up login, registration, and password reset views along with routes and controllers.
2. Registering and Logging In Users
Laravel Breeze provides a complete implementation for user auth. You can access:
/register
for user registration/login
for login/dashboard
as a protected route
Use auth
middleware to restrict access:
Route::middleware('auth')->get('/dashboard', function () {
return view('dashboard');
});
3. Using Laravel Sanctum for API Authentication
✅ Set up Sanctum:
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
Add middleware in app/Http/Kernel.php
under api
group:
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
✅ Token generation:
$user = User::where('email', $request->email)->first();
if ($user && Hash::check($request->password, $user->password)) {
return response()->json([
'token' => $user->createToken('API Token')->plainTextToken
]);
}
4. Protecting Routes with Middleware
✅ Apply middleware to routes:
Route::middleware('auth:sanctum')->group(function () {
Route::get('/profile', function () {
return auth()->user();
});
});
Only authenticated users with valid tokens can access these routes.
5. Implementing Authorization with Gates
✅ Define a gate in AuthServiceProvider
:
Gate::define('edit-post', function ($user, $post) {
return $user->id === $post->user_id;
});
✅ Use the gate:
if (Gate::allows('edit-post', $post)) {
// Allow update
}
6. Using Policies for Complex Authorization
✅ Create a policy:
php artisan make:policy PostPolicy --model=Post
This generates methods like view
, update
, delete
etc.
public function update(User $user, Post $post)
{
return $user->id === $post->user_id;
}
✅ Use in controller or blade:
$this->authorize('update', $post);
7. Role-Based Authorization (Custom Roles)
✅ Add a role column to users table:
$table->string('role')->default('user');
✅ Gate example with roles:
Gate::define('admin-access', function ($user) {
return $user->role === 'admin';
});
8. Blade Directives for Authorization
Use blade directives to show/hide elements based on permissions:
@can('update', $post)
<button>Edit Post</button>
@endcan
Or use:
@auth
<p>Welcome, {{ auth()->user()->name }}</p>
@endauth
9. Logging Out Users
✅ Web logout:
Auth::logout();
✅ API logout (Sanctum):
auth()->user()->currentAccessToken()->delete();
10. Testing Auth Features
public function test_user_can_login()
{
$user = User::factory()->create([
'password' => bcrypt('password123'),
]);
$response = $this->post('/login', [
'email' => $user->email,
'password' => 'password123',
]);
$response->assertRedirect('/dashboard');
}
🧠 Conclusion
Authentication and authorization are essential components of any secure Laravel application. Whether you’re building a full-stack web app or an API backend, Laravel provides flexible tools like Breeze, Sanctum, Gates, and Policies to get the job done effectively.
🔑 Key Takeaways:
- Use Laravel Breeze for simple web authentication.
- Leverage Sanctum for secure token-based API auth.
- Implement fine-grained access control with Gates and Policies.
- Protect routes with middleware and Blade directives.
With these tools in place, your Laravel app will be both secure and scalable! 🔐✨