Laravel Authentication
Authentication is an essential part of modern web applications. Laravel makes implementing authentication simple and efficient with built-in features. This guide will walk you through setting up authentication in Laravel 10/11.
1. What is Laravel Authentication?
Laravel provides a robust authentication system out of the box, including:
- User login & registration
- Password reset functionality
- Email verification
- Role-based authentication
2. Setting Up Authentication in Laravel
Step 1: Install Laravel
If you haven't already installed Laravel, create a new project:
Step 2: Install Laravel Breeze (Simple Authentication Starter Kit)
Laravel Breeze provides authentication scaffolding, including login, registration, password reset, and email verification.
Run the following command to install Breeze:
Then, install the authentication scaffolding:
This command will ask you to select a frontend stack (Blade, Vue, React, etc.). Choose the one that suits your project.
Run migrations to set up the database:
Now, install dependencies and build assets:
Finally, start the server:
Now, visit http://127.0.0.1:8000/register
to see the registration page.
3. Authentication Routes in Laravel
Laravel provides pre-built authentication routes, defined in routes/auth.php
. You can check available routes by running:
This will show routes for login, registration, password reset, and email verification.
4. Customizing Authentication Logic
Changing the Authentication Model
By default, Laravel uses the App\Models\User
model for authentication. You can modify it to add additional fields like roles or permissions.
Example: Adding a role
field in User.php
:
5. Middleware for Authentication and Authorization
Protecting Routes with Middleware
To protect routes from unauthenticated users, use the auth
middleware in routes/web.php
:
If an unauthenticated user tries to access this route, they will be redirected to the login page.
Role-Based Authorization
You can restrict access based on user roles:
Create the AdminMiddleware
file:
Modify app/Http/Middleware/AdminMiddleware.php
:
Register the middleware in Kernel.php
:
6. Email Verification in Laravel
Laravel includes built-in support for email verification. To enable it, ensure your User
model implements MustVerifyEmail
:
Then, update your routes:
This ensures that only verified users can access the dashboard.
7. Resetting Passwords
Laravel provides an easy way to handle password resets. After installing Breeze, you’ll already have routes for resetting the password.
To modify password reset logic, update:
- Email template:
resources/views/auth/passwords/email.blade.php
- Controller logic:
app/Http/Controllers/Auth/ForgotPasswordController.php
Conclusion
🎉 Congratulations! You now have a fully functional authentication system in Laravel. Your application is now secure and user-friendly with authentication, role-based access, and email verification.
💬 Have any questions? Let us know in the comments!