Sechno
Software Development

Laravel 11 Custom Authentication: A Step-by-Step Guide

Learn how to create a custom authentication system in Laravel 11 to secure your application and protect user data.

SSechno Team 4 min read 1214 views
Laravel 11 Custom Authentication: A Step-by-Step Guide

Laravel 11 introduces a range of enhancements to the framework, particularly in the areas of security, flexibility, and authentication systems. While Laravel's built-in authentication options like Breeze, Jetstream, and Fortify simplify the implementation process, there are instances where a tailored approach is necessary to align with your project's specific needs.

In this article, we will explore how to build a personalized authentication system using Laravel 11. This system will deliver key functionalities such as login, registration, password reset, and logout, along with the ability to customize it to meet specific requirements.

Prerequisites

To follow along with this guide, you should:

  • Have Laravel 11 installed.
  • Be familiar with the basics of Laravel, such as routes, controllers, and middleware.

Step 1: Set Up a Laravel Project

1. First, ensure your Laravel project is set up:

composer create-project laravel/laravel my_custom_auth
cd my_custom_auth

2. Migrate your database (using MySQL, SQLite, or your preferred DB) to set up the initial tables:

php artisan migrate

Step 2: Create Custom Routes

In routes/web.php, define routes for registration, login, logout, and password reset.

use App\Http\Controllers\Auth\CustomAuthController;
Route::get('register', [CustomAuthController::class, 'showRegistrationForm'])->name('register');
Route::post('register', [CustomAuthController::class, 'register']);
Route::get('login', [CustomAuthController::class, 'showLoginForm'])->name('login');
Route::post('login', [CustomAuthController::class, 'login']);
Route::post('logout', [CustomAuthController::class, 'logout'])->name('logout');
Route::get('password/reset', [CustomAuthController::class, 'showResetForm'])->name('password.request');
Route::post('password/email', [CustomAuthController::class, 'sendResetLink'])->name('password.email');
Route::post('password/reset', [CustomAuthController::class, 'reset'])->name('password.update');

Step 3: Create a Custom Authentication Controller

In the app/Http/Controllers/Auth directory, create a new controller called CustomAuthController.

php artisan make:controller Auth/CustomAuthController

In CustomAuthController.php, add methods for handling registration, login, and logout functionality.

3.1 Registration

Add a showRegistrationForm and register method to display the registration form and handle user registration.

namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class CustomAuthController extends Controller
{
    public function showRegistrationForm()
    {
        return view('auth.register');
    }
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
        ]);
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);
        auth()->login($user);
        return redirect()->route('dashboard');
    }
}

3.2 Login

Add methods to show the login form and handle user login.

public function showLoginForm()
{
    return view('auth.login');
}
public function login(Request $request)
{
    $credentials = $request->only('email', 'password');
    if (auth()->attempt($credentials)) {
        $request->session()->regenerate();
        return redirect()->intended('dashboard');
    }
    return back()->withErrors([
        'email' => 'The provided credentials do not match our records.',
    ]);
}

3.3 Logout

Add a method to handle logout.

public function logout(Request $request)
{
    auth()->logout();
    $request->session()->invalidate();
    $request->session()->regenerateToken();
    return redirect('/');
}

Step 4: Create Views for Authentication

In resources/views/auth, create register.blade.php and login.blade.php for registration and login forms, respectively.

4.1 register.blade.php

<form method="POST" action="{{ route('register') }}">
    @csrf
    <input type="text" name="name" placeholder="Name" required>
    <input type="email" name="email" placeholder="Email" required>
    <input type="password" name="password" placeholder="Password" required>
    <input type="password" name="password_confirmation" placeholder="Confirm Password" required>
    <button type="submit">Register</button>
</form>

4.2 login.blade.php

<form method="POST" action="{{ route('login') }}">
    @csrf
    <input type="email" name="email" placeholder="Email" required>
    <input type="password" name="password" placeholder="Password" required>
    <button type="submit">Login</button>
</form>

Step 5: Implement Password Reset Functionality

For password resets, you can customize the forms and logic. Here's a simple example of the process:

1. Show reset form:

public function showResetForm()
{
    return view('auth.passwords.email');
}

2. Send password reset link:

public function sendResetLink(Request $request)
{
    // Implement custom password reset link sending logic here
}

3. Reset password:

public function reset(Request $request)
{
    // Implement password reset logic here
}

For a production-grade system, you may want to integrate Laravel's Password::sendResetLink and Password::reset methods to leverage built-in functionality while customizing it as per requirements.

Step 6: Apply Middleware for Route Protection

In routes/web.php, use the auth middleware to restrict access to authenticated users only.

Route::middleware('auth')->group(function () {
    Route::get('/dashboard', function () {
        return view('dashboard');
    })->name('dashboard');
});

Step 7: Test and Customize Further

With the basics set up, you can now run php artisan serve and test your custom authentication system. Add any additional functionality as required for your application, such as social logins, two-factor authentication, or custom access control lists (ACLs).

Conclusion

A custom authentication system in Laravel 11 provides excellent adaptability for customizing security features to align with unique project needs. When you require extra fields for registration or particular validation processes, tailored authentication gives you the authority to establish a secure and distinctive user experience.

Was this helpful?

Share this post

Comments (0)

Want to join the conversation?

Log in or sign up to leave a comment and share your thoughts.

Log in to Comment