Laravel 10 Custom Auth Login and Registration Tutorial

Last Updated on by in Laravel

Laravel is a renowned PHP framework, well-known for its robustness, simplicity, and rich features. The authentication system, which offers default procedures for user login, registration, and session management, is one of its essential parts.

Custom authentication becomes essential when tailoring user authentication processes, implementing additional security layers, or incorporating unique user data verification steps beyond Laravel’s default features.

In this tutorial, you will learn how to create a basic authentication system, and display validation error and success messages through view in Laravel along with Bootstrap 5.

For this, we will create controllers and models, set up custom database tables, integrate frontend views, implement authentication logic, ensure security measures, and perform basic browser testing. It will cover steps to build a simple authentication behavior (User Login auth, User registration or sign up auth).

By the end of this guide, you will understand how to use create a customized authentication system (simple SignIn, SignUp with email and password) that prevents unauthorized users to get access from your system.

Step 1: Setting Up Laravel Project

Use the below command to install the new laravel app.

You can skip this step if the app is already installed.

composer create-project --prefer-dist laravel/laravel laravel_demo_app

Next, head over to app folder:

cd laravel_demo_app

Step 2: Configuring Database Connection

I am using XAMPP for MySQL database, if you don’t have MySQL database, make sure to install and setup XAMPP or WAMP based on your operating system.

Instructions for configuring Laravel to connect with the database:

Add database name, username, and password into the .env:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_user_name
DB_PASSWORD=database_password

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

The laravel app comes with a default User model and migration file, and we only have to run the following command to create the new table inside the database. So, get to the terminal and execute the following command to run the migration.

php artisan migrate

Step 3: Creating Custom Controllers

Type the suggested command on the command prompt and execute the command to generate a new controller file by the name of CustomAuthController.

php artisan make:controller CustomAuthController

Thereafter, open app\Http\Controllers\CustomAuthController.php file and carefully place the following code within the file.

<?php
namespace App\Http\Controllers;

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

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

    public function customLogin(Request $request)
    {
        $request->validate([
            'email' => 'required',
            'password' => 'required',
        ]);

        $credentials = $request->only('email', 'password');
        if (Auth::attempt($credentials)) {
            return redirect()->intended('dashboard')
                ->withSuccess('Signed in');
        }

        return redirect("login")->withSuccess('Login details are not valid');
    }

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

    public function customRegistration(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:6',
        ]);

        $data = $request->all();
        $check = $this->create($data);

        return redirect("dashboard")->withSuccess('You have signed-in');
    }

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

    public function dashboard()
    {
        if (Auth::check()) {
            return view('auth.dashboard');
        }
        return redirect("login")->withSuccess('You are not allowed to access');
    }

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

Step 4: Creating Auth Routes

This step explains how to create routes with POST and GET methods for handling custom authentication in laravel application.

Consequently, open and add the recommended code in the routes/web.php file:

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CustomAuthController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/
Route::get('dashboard', [CustomAuthController::class, 'dashboard'])->name('dashboard');
Route::get('login', [CustomAuthController::class, 'index'])->name('login');
Route::post('custom-login', [CustomAuthController::class, 'customLogin'])->name('login.custom');
Route::get('register', [CustomAuthController::class, 'registration'])->name('register');
Route::post('custom-registration', [CustomAuthController::class, 'customRegistration'])->name('register.custom');
Route::get('signout', [CustomAuthController::class, 'signOut'])->name('signout');

Step 5: Create Auth Blade View Files

Create views files, these files handle login, signup or user registration in Laravel. Make sure to create an auth folder in resources/views/ directory, next create the following files that handles the view for login in Laravel, signup in laravel.

  • layouts.blade.php
  • login.blade.php
  • register.blade.php
  • dashboard.blade.php

Now, create the basic layout that handles the login and registration components, add the given below code in the resources/views/layouts.blade.php file:

<!DOCTYPE html>
<html>

<head>
    <title>Custom Auth in Laravel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    <nav class="navbar navbar-light navbar-expand-lg mb-5" style="background-color: #e3f2fd;">
        <div class="container">
            <a class="navbar-brand mr-auto" href="#">PositronX</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
                aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav">
                    @guest
                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('login') }}">Login</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('register') }}">Register</a>
                    </li>
                    @else
                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('signout') }}">Logout</a>
                    </li>
                    @endguest
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-5">
        @yield('content')
    </div>
</body>

</html>

Step 6: Create Authentication Templates in Laravel

You need to create auth folder in resources/views/ folder likewise create a new login.blade.php file, next place the following code in resources/views/auth/login.blade.php file:

@extends('auth.layouts')
@section('content')
<main class="login-form">
    <div class="cotainer">
        <div class="row justify-content-center">
            <div class="col-md-4">
                <div class="card">
                    <h3 class="card-header text-center">Login</h3>
                    <div class="card-body">
                        <form method="POST" action="{{ route('login.custom') }}">
                            @csrf
                            <div class="form-group mb-3">
                                <input type="text" placeholder="Email" id="email" class="form-control" name="email"
                                    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" placeholder="Password" id="password" class="form-control"
                                    name="password" 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 Me
                                    </label>
                                </div>
                            </div>
                            <div class="d-grid mx-auto">
                                <button type="submit" class="btn btn-dark btn-block">Signin</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>
@endsection

Step 7: Handling User Registration with Validation Logic

You have to move to resources/views/auth folder, create a new register.blade.php file, next add the suggested code in the resources/views/auth/register.blade.php file:

@extends('auth.layouts')
@section('content')
<main class="signup-form">
    <div class="cotainer">
        <div class="row justify-content-center">
            <div class="col-md-4">
                <div class="card">
                    <h3 class="card-header text-center">Register User</h3>
                    <div class="card-body">
                        <form action="{{ route('register.custom') }}" method="POST">
                            @csrf
                            <div class="form-group mb-3">
                                <input type="text" placeholder="Name" id="name" class="form-control" name="name"
                                    required autofocus>
                                @if ($errors->has('name'))
                                <span class="text-danger">{{ $errors->first('name') }}</span>
                                @endif
                            </div>
                            <div class="form-group mb-3">
                                <input type="text" placeholder="Email" id="email_address" class="form-control"
                                    name="email" 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" placeholder="Password" id="password" class="form-control"
                                    name="password" 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 Me</label>
                                </div>
                            </div>
                            <div class="d-grid mx-auto">
                                <button type="submit" class="btn btn-dark btn-block">Sign up</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>
@endsection

Head over to resources/views/auth folder, next add the following code in the resources/views/auth/dashboard.blade.php file:

@extends('auth.layouts')
@section('content')

<div class="row justify-content-center">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header"><strong>Dashboard</strong></div>
            <div class="card-body">
                @if ($message = Session::get('success'))
                <div class="alert alert-success">
                    {{ $message }}
                </div>
                @else
                <div class="alert alert-success">
                    Hello, Admin, You are logged in!
                </div>
                @endif
            </div>
        </div>
    </div>
</div>

@endsection

Step 8: Run Laravel Development Server

Finally, we need to run the laravel development server, which will help us start the app on the browser. Ensure that you execute the given below command through the command prompt.

php artisan serve

Add the following url on the browser’s address bar and test the app.

http://127.0.0.1:8000/register
http://127.0.0.1:8000/login

Laravel custom authentication tutorial

Laravel Security: Best Practices

In Laravel authentication, cross-site request forgery (CSRF) protection plays a vital role in safeguarding against CSRF attacks. CSRF attacks are particularly dangerous because they occur without the user’s explicit consent or interaction.

Using the right CSRF protections, like creating and confirming unique tokens for each user session, can help stop browsers from carrying out requests that aren’t supposed to be there. As a result, this security measure makes sure that requests coming from a verified user really do come from that user. This lowers the risk of CSRF attacks and makes web services safer overall.

Furthermore, Laravel developers can consider the following measures to strictly tighten the security of Laravel authentication that significantly reduce the risk of common security vulnerabilities in their authentication systems, ensuring a more robust and secure application.

Common measures to prevent common security vulnerabilities in Laravel authentication:

  • Use strong password hashing
  • Parameter Binding in Queries
  • Implement CSRF protection
  • Authentication Throttling
  • Secure Session Management
  • Regular Updates
  • Secure configuration and environment

Download Project Code

If you want to download the code of this tutorial, make sure to check the GitHub for complete code example.

Conclusion

Laravel provides robust tools and features to manage authentication processes efficiently.

In this comprehensive guide, we learned how to build user authentication in Laravel, we went over multiple process for the creation of a simple user management system.

We’ve also touched on some best practices for adding an extra security layer to Laravel auth, which gives developers a safe way to authenticate with the right credentials.

Additional Resources

Below are the links to the Laravel documentation, as well as additional important resources for implementing best practices in developing Laravel authentication functionality.

Reference: Laravel Authentication Documentation