Laravel 12 Custom Auth Tutorial: Building Your Own Authentication System
Authentication is a crucial part of any web application. It ensures that only authorized users can access certain parts of your app. Laravel, a popular PHP framework, provides a built-in authentication system out of the box. However, sometimes you might want to build a custom authentication system to fit your specific needs.
In this tutorial, we’ll walk through the process of creating a custom authentication system in Laravel 12. By the end of this guide, you’ll have a fully functional custom auth system that you can tweak as per your requirements.
Prerequisites
-
Laravel Installed: You should have Laravel installed on your machine. If not, you can install it using Composer:
composer create-project --prefer-dist laravel/laravel custom-auth -
Database Setup: Ensure your
.envfile is configured with the correct database credentials. - Basic Laravel Knowledge: Familiarity with Laravel’s routing, controllers, and Blade templates will be helpful.
Step 1: Set Up the Database
First, let’s create a users table in the database. Laravel 12 already provides a migration for this, so we just need to run it.
-
Open the
database/migrations/2014_10_12_000000_create_users_table.phpfile and ensure it looks like this:public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->timestamps(); }); } -
Run the migration:
php artisan migrate
This will create the users table in your database.
Step 2: Create the Auth Controller
Next, let’s create a controller to handle authentication logic.
-
Run the following command to create a new controller:
php artisan make:controller AuthController -
Open the newly created
AuthController.phpfile and add the following methods:<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use App\Models\User; use Illuminate\Support\Facades\Hash; class AuthController extends Controller { // Show the login form public function showLoginForm() { return view('auth.login'); } // Handle login request public function login(Request $request) { $credentials = $request->validate([ 'email' => 'required|email', 'password' => 'required', ]); if (Auth::attempt($credentials)) { $request->session()->regenerate(); return redirect()->intended('/dashboard'); } return back()->withErrors([ 'email' => 'The provided credentials do not match our records.', ]); } // Show the registration form public function showRegisterForm() { return view('auth.register'); } // Handle registration request public function register(Request $request) { $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|string|min:8|confirmed', ]); $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => Hash::make($request->password), ]); Auth::login($user); return redirect('/dashboard'); } // Handle logout request public function logout(Request $request) { Auth::logout(); $request->session()->invalidate(); $request->session()->regenerateToken(); return redirect('/'); } }
Step 3: Create Views for Login and Registration
Now, let’s create the views for login and registration.
- Create a new folder:
resources/views/auth. -
Inside the
authfolder, create two files:login.blade.phpandregister.blade.php.
login.blade.php:
register.blade.php:<!DOCTYPE html> <html> <head> <title>Login</title> </head> <body> <h1>Login</h1> <form method="POST" action="{{ route('login') }}"> @csrf <div> <label for="email">Email</label> <input type="email" name="email" id="email" required> </div> <div> <label for="password">Password</label> <input type="password" name="password" id="password" required> </div> <button type="submit">Login</button> </form> </body> </html><!DOCTYPE html> <html> <head> <title>Register</title> </head> <body> <h1>Register</h1> <form method="POST" action="{{ route('register') }}"> @csrf <div> <label for="name">Name</label> <input type="text" name="name" id="name" required> </div> <div> <label for="email">Email</label> <input type="email" name="email" id="email" required> </div> <div> <label for="password">Password</label> <input type="password" name="password" id="password" required> </div> <div> <label for="password_confirmation">Confirm Password</label> <input type="password" name="password_confirmation" id="password_confirmation" required> </div> <button type="submit">Register</button> </form> </body> </html>
Step 4: Define Routes
Finally, let’s define the routes for our custom authentication system.
<?php
use App\Http\Controllers\AuthController;
// Show login form
Route::get('/login', [AuthController::class, 'showLoginForm'])->name('login');
// Handle login
Route::post('/login', [AuthController::class, 'login']);
// Show registration form
Route::get('/register', [AuthController::class, 'showRegisterForm'])->name('register');
// Handle registration
Route::post('/register', [AuthController::class, 'register']);
// Handle logout
Route::post('/logout', [AuthController::class, 'logout'])->name('logout');
// Protected route (example)
Route::get('/dashboard', function () {
return 'Welcome to the dashboard!';
})->middleware('auth');
Step 5: Test Your Custom Auth System
- Start your Laravel 12 development server:
php artisan serveor
composer run dev - Visit http://localhost:8000/register to create a new account.
- After registration, you’ll be redirected to the dashboard.
- Log out and then log back in using the login form at http://localhost:8000/login.
Conclusion
Congratulations! You’ve successfully built a custom authentication system in Laravel 12.
We swapped out the default User model for a Member model, used a custom members table, and added a phone_number field to the registration process.
This is just the beginning—you can keep customizing by:
- Adding more fields (like address or birthday)
- Changing the login to use phone number instead of email
- Setting up different user types with multiple guards
If you run into issues (such as password resets not working), double-check your config/auth.php settings.
Feel free to tweak the controllers or views further to fit your app’s needs.
Happy coding! Let me know in the comments if you have questions or want to see more Laravel 12 tutorials.
Projects to explore next
Source-code projects from the KritiMyantra catalogue. Check each project's details before buying.
Flask Authentication System (Free Version) - Kritim Yantra
🛠 Features✔ Google & GitHub Authentication✔ User Registration & Login✔ Profile/Dashboard Access✔ Secure & Mi...
Python Flask Blog Project with Admin Panel
Are you ready to launch a powerful, modern, and fully customizable blog? Look no further! Introducing the Flask-Blog Pro...
Laravel 12 + ReactJS Starter Kit: Add Multi-Language Support (Arabic, English, Spanish) with Blog CRUD
🚀 Installation & Setup Download & Extract Get the ZIP from kritimyantra.com and extract it. Includes preconfigu...
Comments
No comments yet. Be the first to comment.
Sign in to join the discussion.