How to Create Custom Auth Login and Registration in Laravel 9

In this extensive laravel custom registration and login tutorial, we will give you an eloquent example on building laravel custom login authentication and laravel custom registration modules.

You will find out how to create custom login and registration authentication in the laravel application without using any external package and that too from the absolute beginning.

User authentication is a mechanism that verifies the identity of a user trying to gain access to a web application to use its resource.

It is a subtle process of authorizing a human to machine based on the credentials (email/password) that confirms a user’s authenticity.

This profound guide will demystify every laravel custom auth aspect, which won’t be apart from the common notion. HTML to CSS or designing to development; rest assured, we will cover all.

Laravel 9 Custom Authentication (Login/Registration) Example

  • Step 1: Download Laravel Project
  • Step 2: Add Database Credentials in ENV
  • Step 3: Create New Controller
  • Step 4: Register New Routes
  • Step 5: Create Auth View Templates
  • Step 6: Start Application

Download Laravel Project

The inception of this guide starts with downloading a new laravel application with the help of provided command.

After creating the project, get inside its root.

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

Add Database Credentials in ENV

Auth credentials stays in the database, therefore it is necessary to update the .env file with database credentials.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=DB_Name
DB_USERNAME=DB_Username
DB_PASSWORD=DB_Password

You don’t have to generate Model and Migration, laravel new app provides default users model and migration pre-configured.

Here is the command that needs to be run from the console, to migrate the users’ table into the database.

php artisan migrate

Create New Controller

The controller is the file, which is the locus of a single class; within this class, you may add various functions for handling a specific task.

Consequently, use provided command to generate a new controller.

php artisan make:controller AuthController

In this section, you have to head over to app\Http\Controllers\AuthController.php and update with the given functions or code.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Session;
use Hash;


class AuthController extends Controller
{
    public function index()
    {
        return view('auth.signin');
    }  
      

    public function createSignin(Request $request)
    {
        $request->validate([
            'email' => 'required',
            'password' => 'required',
        ]);
        $credentials = $request->only('email', 'password');
        if (Auth::attempt($credentials)) {
            return redirect()->intended('dashboard')
                        ->withSuccess('Logged-in');
        }
        return redirect("login")->withSuccess('Credentials are wrong.');
    }


    public function signup()
    {
        return view('auth.signup');
    }
      

    public function customSignup(Request $request)
    {  
        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:6',
        ]);
        $data = $request->all();
        $check = $this->createUser($data);
        return redirect("dashboard")->withSuccess('Successfully logged-in!');
    }


    public function createUser(array $data)
    {
      return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password'])
      ]);
    }    
    

    public function dashboardView()
    {
        if(Auth::check()){
            return view('auth.dashboard');
        }
        return redirect("login")->withSuccess('Access is not permitted');
    }
    

    public function logout() {
        Session::flush();
        Auth::logout();
        return Redirect('login');
    }
}

Register New Routes

Define new routes in routes/web.php, these routes will enable the processing of auth templates defined in the controller file.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/login', [AuthController::class, 'index'])->name('login');
Route::post('/custom-signin', [AuthController::class, 'createSignin'])->name('signin.custom');


Route::get('/register', [AuthController::class, 'signup'])->name('register');
Route::post('/create-user', [AuthController::class, 'customSignup'])->name('user.registration');


Route::get('/dashboard', [AuthController::class, 'dashboardView'])->name('dashboard');
Route::get('/logout', [AuthController::class, 'logout'])->name('logout');

Create Auth View Templates

In the last section of this guide, we will understand how to prepare blade view files for building login, and registration system.

Step inside the resources/views/auth directory, and respectively create following files:

=> signup.blade.php

=> signin.blade.php

=> dashboard.blade.php

You are ready to give the final touch to the auth files.

Update resources/views/auth/signup.blade.php file:

@extends('app')

@section('content')
<main class="cotainer mt-5">
        <div class="row justify-content-center">
            <div class="col-md-4">
                <div class="card">
                    <h3 class="card-header text-center">Signup</h3>
                    <div class="card-body">
                        <form action="{{ route('user.registration') }}" method="POST">
                            @csrf
                            <div class="form-group mb-3">
                                <input type="text" name="name" placeholder="Name" id="name" class="form-control">
                                @if ($errors->has('name'))
                                <span class="text-danger">{{ $errors->first('name') }}</span>
                                @endif
                            </div>

                            <div class="form-group mb-2">
                                <input type="text" name="email" placeholder="Email" id="email_address" class="form-control">
                                @if ($errors->has('email'))
                                <span class="text-danger">{{ $errors->first('email') }}</span>
                                @endif
                            </div>

                            <div class="form-group mb-2">
                                <input type="password" name="password" placeholder="Password" id="password" class="form-control">
                                @if ($errors->has('password'))
                                <span class="text-danger">{{ $errors->first('password') }}</span>
                                @endif
                            </div>

                            <div class="form-group mb-2">
                                <div class="checkbox">
                                    <label><input type="checkbox" name="remember">Remember</label>
                                </div>
                            </div>

                            <div class="d-grid mx-auto">
                                <button type="submit" class="btn btn-primary btn-block">Register</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
</main>
@endsection

Update resources/views/auth/signin.blade.php file:

@extends('app')

@section('content')
<main class="cotainer mt-5">
        <div class="row justify-content-center">
            <div class="col-md-5">
                <div class="card">
                    <h3 class="card-header text-center">Signin</h3>
                    <div class="card-body">
                        <form method="POST" action="{{ route('signin.custom') }}">
                            @csrf
                            <div class="form-group mb-3">
                                <input type="text" name="email" placeholder="Email" id="email" class="form-control" required
                                    autofocus>
                                @if ($errors->has('email'))
                                <span class="text-danger">{{ $errors->first('email') }}</span>
                                @endif
                            </div>

                            <div class="form-group mb-3">
                                <input type="password" name="password" placeholder="Password" id="password" class="form-control" required>
                                @if ($errors->has('password'))
                                <span class="text-danger">{{ $errors->first('password') }}</span>
                                @endif
                            </div>

                            <div class="form-group mb-3">
                                <div class="checkbox">
                                    <label>
                                        <input type="checkbox" name="remember">Remember
                                    </label>
                                </div>
                            </div>
                            <div class="d-grid mx-auto">
                                <button type="submit" class="btn btn-success">Login</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
</main>
@endsection

Update resources/views/auth/dashboard.blade.php file:

@extends('app')

@section('content')

    <div class="container mt-5" style="max-width: 500px">
        <div class="d-grid">
          <a href="{{ route('logout') }}" class="btn btn-danger">Sign-out</a>
        </div>  
    </div>

@yield('content')
@endsection

In the last section, you have to create the app.blade.php file inside the resources/views folder, there after update the resources/views/app.blade.php with the given code.

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Custom Login/Signup Example</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    @yield('content')
</body>

</html>

Start Application

The provided command starts the laravel app, register the user to gain access to the app.

php artisan serve

http://127.0.0.1:8000/login

http://127.0.0.1:8000/register

http://127.0.0.1:8000/dashboard

laravel custom signin/signup

Conclusion

This guide has almost finished; we have respectively explained how to create custom login and registration in the laravel application.

However, this was just the tip of to iceberg. You can add many more features to it to make it more robust from a security perspective.

If you try so, you can also enhance the web application authorization using JWT authentication, role-based access control etc.

But this tutorial is good to start with custom auth in laravel, especially for beginners.