Laravel Custom Authentication Login and Registration With Middleware

Laravel Custom Authentication Login and Registration With Middleware

In modern web applications, authentication is a crucial component. Laravel, with its powerful authentication system, makes it easy to set up basic login and registration functionality. However, sometimes you might need a custom authentication flow tailored to your specific requirements. In this article, we’ll walk through how to implement custom authentication and registration in Laravel using middleware.

Laravel Custom Authentication Login And Registration With Middleware

Step 1: Setting Up Laravel Project

First, ensure you have Composer installed. Then, create a new Laravel project:

composer create-project laravel/laravel customerauth

Step 2: Database Configuration

Set up your database by configuring the .env file with your database details:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_custom_auth
DB_USERNAME=root
DB_PASSWORD=

Step 3: Create the config files

In this step, I created a new model, route, and migration files. So I have not used the default files.

Step 4: Config the create files

First, modify the migration files.


    <?php

    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;
    return new class extends Migration
    {
        public function up(): void
        {
            Schema::create('customers', function (Blueprint $table) {
                $table->id();
                $table->string('name')->nullable();
                $table->string('email')->unique();
                $table->bigInteger('contact')->nullable();
                $table->string('password')->nullable();
                $table->date('password_update_date')->nullable();
                $table->integer('email_varification_status')->default(0);
                $table->date('email_varification_date')->nullable();
                $table->integer('status')->default(0);
                $table->softDeletes();
                $table->timestamps();
            });
        }
        public function down(): void
        {
            Schema::dropIfExists('customers');
        }
    };


This Laravel migration script creates a customer table with several fields: id as the primary key, name (nullable), email (unique), contact (nullable), password (nullable), password_update_date (nullable), email_verification_status (default 0), email_verification_date (nullable), and status (default 0). It also includes softDeletes for soft deletion capability and timestamps for created_at and updated_at. The up method defines the table structure, while the down method drops the table if it exists, allowing for easy migration and rollback of database changes.

After migration files, modify the model files.


    <?php
    namespace App\Models;
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\SoftDeletes;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Notifications\Notifiable;
    class Customer extends Authenticatable
    {
        use HasFactory, Notifiable;
        protected $table = 'customers';
        protected $fillable = ['name', 'email', 'contact', 'password', 'password_update_date', 'email_varification_status', 'email_varification_date', 'status'];
    }

This Laravel model class represents the Customer entity and is designed to interact with the customer's table in the database. The class extends Authenticatable, allowing it to be used for authentication purposes. It utilizes the HasFactory and Notifiable traits for factory-based instantiation and notification capabilities, respectively. The $table property specifies that this model corresponds to the customer's table. The $fillable property is an array that lists the attributes (name, email, contact, password, password_update_date, email_verification_status, email_verification_date, status) that can be mass-assigned, ensuring security and ease of use when creating or updating Customer records.

Step 5: Create the Authentication and Dashboard Controller

php artisan make:controller Customer/Auth/CustomerController
php artisan make:controller Customer/DashboardController.php

In the CustomerController add methods for handling registration, login, and logout and  In the DashboardController add the method for handling the dashboard.
CustomerController


    <?php
    namespace App\Http\Controllers\Customer\Auth;
    use App\Http\Controllers\Controller;
    use Illuminate\Http\Request;
    use App\Models\Customer;
    use Auth;
    use Hash;
    use Session;
    class CustomerController extends Controller
    {
        public function register()
        {
            return view('Customer.Auth.register');
        }
        public function registerSubmit(Request $request){
            $request->validate([
                "name" => "required|min:3|string",
                "email" => "required|email|unique:customers,email",
                "contact" => "required|numeric",
                "password" => "required|min:6",
                "confirmpassword" => "required|min:6|same:password",
            ]);
            $customerRegister = new Customer();
            $customerRegister->name = $request->input('name');
            $customerRegister->email = $request->input('email');
            $customerRegister->contact = $request->input('contact');
            $customerRegister->password = Hash::make($request->input('password'));
            $customerRegister->save();
            if ($customerRegister) {
                if (Auth::guard('customer')->attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) {
                    Session::put('loggedin', true);
                    Session::put($request->input('email'), true);
                    return redirect()->route('customer.dashboard')->with('success', 'Registration Complete');
                } else {
                    return redirect()->back()->with('error', 'Registration not complete, something wrong');
                }
            } else {
                return redirect()->back()->with('error', 'Registration not complete, something wrong');
            }
        }
        public function login()
        {
            return view('Customer.Auth.login');
        }
        public function loginSubmit(request $request)
        {
            $request->validate([
                "email" => "required|email",
                "password" => "required|min:6",
            ]);
            if (Auth::guard('customer')->attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) {
                Session::put('loggedin', true);
                Session::put($request->input('email'), true);
                return redirect()->route('customer.dashboard')->with('success', 'Login Success');
            } else {
                return redirect()->back()->with('error', 'Login failed, something wrong');
            }
        }
        public function logout()
        {
            Auth::guard('customer')->logout();
            Session::forget('loggedin');
            return redirect()->route('customer.login')->with('success', 'Logged out successfully');
        }
    }

DashboardController


    <?php
    namespace App\Http\Controllers\Customer;
    use App\Http\Controllers\Controller;
    use Illuminate\Http\Request;
    use Auth;
    use Hash;
    use Session;
    use App\Models\Customer;
    class DashboardController extends Controller
    {
        public function dashboard()
        {
            if(Auth::guard('customer')->check())
            {
                return view('Customer.Dashboard');
            }
            else
            {
                return redirect()->route('customer.login');
            }
        }
    }

Step 6: Route Code

Auth route file


    <?php
    use Illuminate\Support\Facades\Route;
    use App\Http\Controllers\Customer\Auth\CustomerController;
    use App\Http\Middleware\CustomerNotAuth;
    use App\Http\Middleware\CustomerAuth;
    Route::prefix('customer')->middleware('iscustomernotAuth')->group(function () {
        Route::get('/register', [CustomerController::class, 'register'])->name('customer.register');
        Route::post('/register/submit', [CustomerController::class, 'registerSubmit'])->name('customer.register.submit');
        Route::get('/login', [CustomerController::class, 'login'])->name('customer.login');
        Route::post('/login/submit', [CustomerController::class, 'loginSubmit'])->name('customer.login.submit');
    });
    Route::get('/logout', [CustomerController::class, 'logout'])->name('customer.logout');

Dashboard route file


    <?php
    use Illuminate\Support\Facades\Route;
    use App\Http\Controllers\Customer\Auth\CustomerController;
    use App\Http\Controllers\Customer\DashboardController;
    Route::prefix('customer')->middleware('iscustomerAuth')->group(function () {
        route::get('/dashboard', [DashboardController::class, 'dashboard'])->name('customer.dashboard');
    });

Step 7: Registration and login form

Create the views for registration and login:
resources/views/Customer/auth/register.blade.php

Registration Form

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Laravel | Auth</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Dancing+Script:wght@400..700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="{{asset('Customer/css/style.css')}}">
</head>
<body>
    <div class="form-section">
        <div class="box1">
            <h3>Laravel Custom Auth <span>RAYS CODING</span></h3>
        </div>
        <div class="box2">
            <div class="content">
                <div class="content-header">
                    <div class="container">
                        <div class="row">
                            <div class="col-lg-6">
                                <p>Create Account</p>
                            </div>
                            <div class="col-lg-6">
                                <a href="{{route('customer.login')}}">Already Registered</a>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="content-body">
                    <div class="container">
                        <div class="row">
                            <form action="{{route('customer.register.submit')}}" method="post">
                                @csrf
                                @if ($errors->any())
                                    @foreach ($errors->all() as $error)
                                        <p class="alert alert-danger">{{ $error }}</p>
                                    @endforeach
                                @endif
                                <div class="row mb-3">
                                    <div class="col-lg-12">
                                        <label for="">Name</label>
                                        <input type="text" name="name" id="name" class="form-control" autocomplete="off" value="{{old('name')}}">
                                    </div>
                                </div>
                                <div class="row mb-3">
                                    <div class="col-lg-12">
                                        <label for="">Email</label>
                                        <input type="email" name="email" id="email" class="form-control" autocomplete="off" value="{{old('email')}}">
                                    </div>
                                </div>
                                <div class="row mb-3">
                                    <div class="col-lg-12">
                                        <label for="">Contact</label>
                                        <input type="text" name="contact" id="contact" class="form-control" autocomplete="off" value="{{old('contact')}}">
                                    </div>
                                </div>
                                <div class="row mb-3">
                                    <div class="col-lg-12">
                                        <label for="">Password</label>
                                        <input type="password" name="password" id="password" class="form-control" autocomplete="off" >
                                    </div>
                                </div>
                                <div class="row mb-3">
                                    <div class="col-lg-12">
                                        <label for="">Confirm Password</label>
                                        <input type="password" name="confirmpassword" id="confirmpassword" class="form-control" autocomplete="off">
                                    </div>
                                </div>
                                <div class="row mb-3">
                                    <div class="col-lg-12">
                                        <button type="submit" class="btn registerbutton w-100">SUBMIT</button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="{{asset('Customer/js/index.js')}}"></script>
</body>
</html>

Laravel Custom Authentication Login and Registration With Middleware

resources/views/Customer/auth/login.blade.php

Login Form

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Laravel | Auth</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Dancing+Script:wght@400..700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="{{asset('Customer/css/style.css')}}">
</head>
<body>
    <div class="form-section-login">
        <div class="box1">
            <h3>Laravel Custom Auth <br><span>RAYS CODING</span></h3>
        </div>
        <div class="box2">
            <div class="content">
                <div class="content-header">
                    <div class="container">
                        <div class="row">
                            <form action="{{route('customer.login.submit')}}" method="post">
                                @csrf
                                @if ($errors->any())
                                    @foreach ($errors->all() as $error)
                                        <p class="alert alert-danger">{{ $error }}</p>
                                    @endforeach
                                @endif
                                <div class="row mb-3">
                                    <div class="col-lg-12">
                                        <label for="">Email</label>
                                        <input type="email" name="email" id="email" class="form-control" autocomplete="off" value="{{old('email')}}">
                                    </div>
                                </div>
                                <div class="row mb-3">
                                    <div class="col-lg-12">
                                        <label for="">Password</label>
                                        <input type="password" name="password" id="password" class="form-control" autocomplete="off" >
                                    </div>
                                </div>
                                <div class="row mb-3">
                                    <div class="col-lg-12">
                                        <button type="submit" class="btn loginbutton w-100">SUBMIT</button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                <div class="content-body">
                    <div class="container">
                        <a href="{{route('customer.register')}}" class="centered-link">Create New Account</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="{{asset('Customer/js/index.js')}}"></script>
</body>
</html>

Laravel Custom Authentication Login And Registration With Middleware

Conclusion

In this article, we've implemented a custom authentication system in Laravel using controllers and middleware. This setup allows you to tailor the authentication flow to your specific needs, providing flexibility beyond the default Laravel authentication scaffolding.

Feel free to further customize the registration and login processes, add additional fields, or enhance validation rules to fit your application’s requirements.

Post a Comment

Previous Post Next Post

Recent in Technology