Laravel 12: Custom Login with Validation and Role Redirects

Hi, I’m a web developer passionate about building secure and user-friendly apps with Laravel. In this article, I’ll show you how to customize a login form in Laravel 12, add validation, and set up role-based redirects.

Whether you’re new to Laravel or a seasoned coder, this guide is easy to follow. With Laravel 12’s powerful features, creating a tailored login system is simple and fun.

Let’s dive in and create a secure login page that directs users based on their roles!

Why Customize the Laravel 12 Login Page?

Laravel 12, released in early 2025, offers a robust authentication system out of the box. However, customizing the login page allows you to enhance user experience, enforce strong validation, and redirect users to specific dashboards based on their roles (e.g., admin, user).

This not only improves security but also makes your application more professional and engaging.

Step-by-Step Guide to Customize Laravel 12 Login Page

Laravel 12: Custom Login with Validation and Role Redirects

Step 1: Set Up Laravel 12 Project

First, ensure you have Laravel 12 installed. Use Composer to create a new project:

composer create-project --prefer-dist laravel/laravel laravel-login
cd laravel-login

Run the development server:

php artisan serve

This sets up a fresh Laravel 12 application. Ensure you have PHP 8.2+ and Composer installed.

Step 2: Install Laravel Breeze for Authentication

Laravel Breeze provides a simple way to scaffold authentication. Install it using:

composer require laravel/breeze --dev
php artisan breeze:install
npm install && npm run dev
php artisan migrate

This command sets up login, registration, and other authentication features. It also generates Blade templates and routes in routes/web.php.

Step 3: Customize the Login Form

The default login form is located at resources/views/auth/login.blade.php. Let’s modify it to add a custom design and fields. Update the file with:

<x-guest-layout>
    <x-auth-card>
        <x-slot name="logo">
            <a href="/" class="text-2xl font-bold">MyApp</a>
        </x-slot>

        <form method="POST" action="{{ route('login') }}" class="space-y-6">
            @csrf
            <div>
                <x-label for="email" :value="__('Email Address')" />
                <x-input id="email" class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autofocus />
                @error('email') <span class="text-red-600">{{ $message }}</span> @enderror
            </div>

            <div>
                <x-label for="password" :value="__('Password')" />
                <x-input id="password" class="block mt-1 w-full" type="password" name="password" required />
                @error('password') <span class="text-red-600">{{ $message }}</span> @enderror
            </div>

            <div class="flex items-center justify-between">
                <label for="remember_me" class="inline-flex items-center">
                    <input id="remember_me" type="checkbox" class="rounded" name="remember">
                    <span class="ml-2 text-sm">{{ __('Remember Me') }}</span>
                </label>
                @if (Route::has('password.request'))
                    <a class="text-sm text-blue-600 hover:underline" href="{{ route('password.request') }}">
                        {{ __('Forgot Password?') }}
                    </a>
                @endif
            </div>

            <x-button class="w-full">
                {{ __('Log In') }}
            </x-button>
        </form>
    </x-auth-card>
</x-guest-layout>

This code adds a clean, modern login form with Tailwind CSS styling (included with Breeze). The @error directives display validation errors.

Step 4: Add Validation Rules

Laravel’s validation ensures secure and valid user input. Create a custom form request for login validation:

php artisan make:request LoginRequest

Edit app/Http/Requests/LoginRequest.php:

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class LoginRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'email' => 'required|email|max:255',
            'password' => 'required|min:8',
        ];
    }

    public function messages()
    {
        return [
            'email.required' => 'Please enter your email address.',
            'email.email' => 'Please enter a valid email address.',
            'password.required' => 'Please enter your password.',
            'password.min' => 'Password must be at least 8 characters.',
        ];
    }
}

Update the AuthenticatedSessionController (app/Http/Controllers/Auth/AuthenticatedSessionController.php) to use this request:

use App\Http\Requests\LoginRequest;

public function store(LoginRequest $request)
{
    $request->authenticate();
    $request->session()->regenerate();
    return redirect()->intended($this->redirectTo());
}

This ensures the login form validates the email and password before authentication.

Step 5: Set Up Role-Based Redirects

To redirect users based on roles, add a role column to the users table. Create a migration:

php artisan make:migration add_role_to_users_table

Edit the migration file (database/migrations/XXXX_add_role_to_users_table.php):

Schema::table('users', function (Blueprint $table) {
    $table->string('role')->default('user');
});

Run the migration:

php artisan migrate

Update the User model (app/Models/User.php):

class User extends Authenticatable
{
    protected $fillable = [
        'name', 'email', 'password', 'role',
    ];
}

Create a middleware for role-based redirects:

php artisan make:middleware RedirectBasedOnRole

Edit app/Http/Middleware/RedirectBasedOnRole.php:

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class RedirectBasedOnRole
{
    public function handle(Request $request, Closure $next)
    {
        if (Auth::check()) {
            $role = Auth::user()->role;
            if ($role === 'admin') {
                return redirect()->route('admin.dashboard');
            } elseif ($role === 'user') {
                return redirect()->route('user.dashboard');
            }
        }
        return $next($request);
    }
}

Register the middleware in app/Http/Kernel.php:

protected $middlewareAliases = [
    'role.redirect' => \App\Http\Middleware\RedirectBasedOnRole::class,
];

Apply the middleware in AuthenticatedSessionController:

protected function redirectTo()
{
    return route('home'); // Temporary route
}

Update routes/web.php to include dashboard routes:

Route::get('/admin/dashboard', function () {
    return view('admin.dashboard');
})->name('admin.dashboard')->middleware('role.redirect');

Route::get('/user/dashboard', function () {
    return view('user.dashboard');
})->name('user.dashboard')->middleware('role.redirect');

Create simple dashboard views (resources/views/admin/dashboard.blade.php and resources/views/user/dashboard.blade.php):

<!-- admin/dashboard.blade.php -->
<x-app-layout>
    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 bg-white border-b border-gray-200">
                    Welcome to the Admin Dashboard!
                </div>
            </div>
        </div>
    </div>
</x-app-layout>
<!-- user/dashboard.blade.php -->
<x-app-layout>
    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 bg-white border-b border-gray-200">
                    Welcome to the User Dashboard!
                </div>
            </div>
        </div>
    </div>
</x-app-layout>

Step 6: Test the Login System

  • Register a user with role admin or user (you can manually set the role in the database or create a registration form with role selection).
  • Log in with valid credentials. The system should validate inputs and redirect to the appropriate dashboard.
  • Test invalid inputs (e.g., wrong email format) to ensure validation errors display.

Best Practices for Laravel 12 Login Page

  • Security: Use Laravel’s secureValidate() for stronger password rules if needed.
  • SEO: Add meta tags to your login page for better search visibility.
  • Performance: Optimize database queries and use caching for faster authentication.
  • User Experience: Ensure the login form is responsive and accessible.

Conclusion

Customizing the Laravel 12 login page with validation and role-based redirects is straightforward with Laravel’s powerful tools like Breeze and middleware.

This guide walked you through setting up a secure, user-friendly login system that enhances your application’s functionality.

By following these steps, you can create a professional login experience that caters to different user roles, boosting engagement and security.

Start implementing these techniques in your Laravel 12 projects to take your web development skills to the next level!

Frequently Asked Questions (FAQs)

Q1: What is the benefit of customizing the Laravel 12 login page?
A: Customizing the login page improves user experience, adds robust validation, and allows role-based redirects for personalized dashboards, enhancing security and engagement.

Q2: How do I add more roles in Laravel 12?
A: Add roles to the users table and update the RedirectBasedOnRole middleware to handle additional roles with specific redirect routes.

Q3: Can I use Laravel Fortify instead of Breeze?
A: Yes, Laravel Fortify provides similar authentication features. However, Breeze includes pre-built Blade templates, making it easier for beginners.

Q4: How do I secure my Laravel 12 login page?
A: Use strong validation rules, enable CSRF protection, hash passwords with Bcrypt, and consider Laravel’s secureValidate() for enhanced security.

Q5: Why are my validation errors not showing?
A: Ensure your Blade template includes @error directives and that the form request is correctly applied in the controller.

For more detailed information, refer to the official Laravel Authentication Docs.


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS