Laravel Custom Authentication | Registration, Login, Logout Process | Laravel login with session
Laravel is a powerful PHP framework that provides developers with the tools needed to build robust web applications quickly. One of the core features Laravel offers is its built-in authentication system, which allows you to manage user login and logout with minimal setup. However, there are situations where you might need to customize these functions to meet specific requirements. In this article, weโll walk through the steps to create a custom login and logout function in Laravel, giving you full control over the authentication process.
Understanding Laravel’s Default Authentication
Before diving into custom solutions, itโs helpful to understand how Laravelโs default authentication works. Laravelโs default authentication system comes with pre-built routes, controllers, and views to handle user login, registration, and password management. This system uses middleware to protect routes and ensure only authenticated users can access certain parts of your application.
The Auth facade
in Laravel provides several helper methods for handling authentication, including:
Auth::attempt()
: Attempts to log the user in with provided credentials.Auth::check()
: Checks if the user is currently authenticated.Auth::logout()
: Logs the user out by clearing the session.
These methods make it easy to implement standard authentication features, but for more complex use cases, you may need to build your own custom functions.
Why Create Custom Login and Logout Functions?
Customizing the login and logout process allows you to:
- Add Additional Logic: Implement business-specific requirements, such as logging login attempts or integrating with third-party services.
- Use Different Fields: Allow users to log in with a username, phone number, or another unique identifier instead of the default email and password.
- Customize Error Handling: Provide more informative or branded error messages to improve the user experience.
- Enhance Security: Introduce additional security measures like throttling, CAPTCHA, or two-factor authentication.
Setting Up Your Laravel Project
To start, ensure you have a Laravel project set up. If you donโt have one yet, you can create a new Laravel project using Composer:
composer create-project --prefer-dist laravel/laravel custom-auth
Once your project is ready, set up your database by updating the .env
file with your database credentials:
DB_DATABASE=custom_auth DB_USERNAME=root DB_PASSWORD=your_password
Then, migrate the default user table to your database:
php artisan migrate
Creating Custom Login Functionality
Step 1: Define Routes
First, you need to define routes for your custom login in routes/web.php
:
Route::get('login', 'Auth\CustomLoginController@showLoginForm')->name('login'); Route::post('login', 'Auth\CustomLoginController@login');
These routes will direct users to the custom login form and handle the login request.
Step 2: Create the Login Controller
Next, create a new controller for handling the login logic:
php artisan make:controller Auth/CustomLoginController
In this controller, add methods to show the login form and handle the login process:
namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class CustomLoginController extends Controller { public function showLoginForm() { return view('auth.login'); } public function login(Request $request) { // Validate the form data $request->validate([ 'email' => 'required|email', 'password' => 'required|string|min:8', ]); // Attempt to log the user in if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) { // If successful, redirect to their intended location return redirect()->intended('dashboard'); } // If unsuccessful, redirect back with an error message return back()->withErrors([ 'email' => 'The provided credentials do not match our records.', ]); } }
Step 3: Create the Login View
In the resources/views/auth
directory, create a login.blade.php
file for your custom login form:
@extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header">{{ __('Login') }}</div> <div class="card-body"> <form method="POST" action="{{ route('login') }}"> @csrf <div class="form-group row"> <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label> <div class="col-md-6"> <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autofocus> @error('email') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row"> <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label> <div class="col-md-6"> <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required> @error('password') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row mb-0"> <div class="col-md-8 offset-md-4"> <button type="submit" class="btn btn-primary"> {{ __('Login') }} </button> </div> </div> </form> </div> </div> </div> </div> </div> @endsection
This form collects the userโs email and password and submits it to the custom login route.
Step 4: Test the Login Process
You can now test the custom login functionality by running your Laravel development server:
php artisan serve
Visit http://localhost:8000/login
, and try logging in with a registered user. If everything is set up correctly, you should be redirected to the dashboard after a successful login.
Creating Custom Logout Functionality
Step 1: Define the Logout Route
Add a logout route to routes/web.php
:
Route::post('logout', 'Auth\CustomLoginController@logout')->name('logout');
This route will handle the logout request.
Step 2: Implement the Logout Method
In your CustomLoginController
, add a method to handle the logout process:
public function logout(Request $request) { Auth::logout(); $request->session()->invalidate(); $request->session()->regenerateToken(); return redirect('/'); }
This method logs the user out by clearing their session and redirecting them to the homepage.
Step 3: Add a Logout Button
To trigger the logout, you can add a logout button to your application’s navigation or dashboard:
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;"> @csrf </form> <a href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> {{ __('Logout') }} </a>
This button will send a POST request to the logout route when clicked, effectively logging the user out.
Step 4: Test the Logout Process
Finally, test the logout functionality by logging in as a user and then logging out using the button you just created. After logging out, you should be redirected to the homepage, and your session should be invalidated.
Creating custom login and logout functions in Laravel gives you the flexibility to tailor the authentication process to your applicationโs unique requirements. Whether you need to add additional validation, use different login credentials, or implement custom security measures, Laravel provides the tools to do so efficiently.
How can I customize the default Laravel authentication?
Customizing the default Laravel authentication involves modifying the default controllers, routes, and views, or creating entirely new ones to suit your specific needs.
Is it safe to handle custom authentication without using Laravelโs built-in features?
Yes, it is safe as long as you follow security best practices, such as proper data validation, password hashing, and implementing measures like CSRF protection.
What are the best practices for storing user passwords securely?
Always hash passwords using algorithms like Bcrypt or Argon2, and never store passwords in plain text.
Can I implement social media login in a custom Laravel authentication system?
Yes, you can integrate social media login by using Laravel Socialite or similar packages to handle OAuth authentication.
How do I integrate multi-factor authentication into my custom authentication system?
Multi-factor authentication can be integrated by using packages that support 2FA, or by manually implementing methods to send one-time passwords (OTPs) to users via email or SMS.