Skip to content
logo1

Appfinz Tech Blogs

Javascript, Laravel, Jquery, Vue Js, Node Js Blogs

Primary Menu logo1

Appfinz Tech Blogs

  • PHP
  • Laravel
  • React
  • React Native
  • Payment Gateway
  • Javascript
  • Jquery
  • Shopify
  • WordPress
  • Angular JS
  • Vue JS
  • Website Trends
  • SEO
  • Node JS
  • Home
  • PHP
  • Laravel
  • Laravel Custom Authentication | Registration, Login, Logout Process | Laravel login with session
  • Laravel

Laravel Custom Authentication | Registration, Login, Logout Process | Laravel login with session

10 months ago
Laravel Custom Authentication | Registration, Login, Logout Process | Laravel login with session

Loading

Laravel is a powerful PHP framework that provides developers with the tools needed to build robust web applications quickly. One of the core features Laravel offers is its built-in authentication system, which allows you to manage user login and logout with minimal setup. However, there are situations where you might need to customize these functions to meet specific requirements. In this article, weโ€™ll walk through the steps to create a custom login and logout function in Laravel, giving you full control over the authentication process.

Understanding Laravel’s Default Authentication

Before diving into custom solutions, itโ€™s helpful to understand how Laravelโ€™s default authentication works. Laravelโ€™s default authentication system comes with pre-built routes, controllers, and views to handle user login, registration, and password management. This system uses middleware to protect routes and ensure only authenticated users can access certain parts of your application.

The Auth facade in Laravel provides several helper methods for handling authentication, including:

  • Auth::attempt(): Attempts to log the user in with provided credentials.
  • Auth::check(): Checks if the user is currently authenticated.
  • Auth::logout(): Logs the user out by clearing the session.

These methods make it easy to implement standard authentication features, but for more complex use cases, you may need to build your own custom functions.

Why Create Custom Login and Logout Functions?

Customizing the login and logout process allows you to:

  • Add Additional Logic: Implement business-specific requirements, such as logging login attempts or integrating with third-party services.
  • Use Different Fields: Allow users to log in with a username, phone number, or another unique identifier instead of the default email and password.
  • Customize Error Handling: Provide more informative or branded error messages to improve the user experience.
  • Enhance Security: Introduce additional security measures like throttling, CAPTCHA, or two-factor authentication.

Setting Up Your Laravel Project

To start, ensure you have a Laravel project set up. If you donโ€™t have one yet, you can create a new Laravel project using Composer:

composer create-project --prefer-dist laravel/laravel custom-auth

Once your project is ready, set up your database by updating the .env file with your database credentials:

DB_DATABASE=custom_auth
DB_USERNAME=root
DB_PASSWORD=your_password

Then, migrate the default user table to your database:

php artisan migrate

Creating Custom Login Functionality

Step 1: Define Routes

First, you need to define routes for your custom login in routes/web.php:

Route::get('login', 'Auth\CustomLoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\CustomLoginController@login');

These routes will direct users to the custom login form and handle the login request.

Step 2: Create the Login Controller

Next, create a new controller for handling the login logic:

php artisan make:controller Auth/CustomLoginController

In this controller, add methods to show the login form and handle the login process:

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

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

    public function login(Request $request)
    {
        // Validate the form data
        $request->validate([
            'email' => 'required|email',
            'password' => 'required|string|min:8',
        ]);

        // Attempt to log the user in
        if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
            // If successful, redirect to their intended location
            return redirect()->intended('dashboard');
        }

        // If unsuccessful, redirect back with an error message
        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ]);
    }
}

Step 3: Create the Login View

In the resources/views/auth directory, create a login.blade.php file for your custom login form:

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Login') }}</div>

                <div class="card-body">
                    <form method="POST" action="{{ route('login') }}">
                        @csrf

                        <div class="form-group row">
                            <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autofocus>

                                @error('email')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required>

                                @error('password')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="form-group row mb-0">
                            <div class="col-md-8 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Login') }}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

This form collects the userโ€™s email and password and submits it to the custom login route.

Step 4: Test the Login Process

You can now test the custom login functionality by running your Laravel development server:

php artisan serve

Visit http://localhost:8000/login, and try logging in with a registered user. If everything is set up correctly, you should be redirected to the dashboard after a successful login.

Creating Custom Logout Functionality

Step 1: Define the Logout Route

Add a logout route to routes/web.php:

Route::post('logout', 'Auth\CustomLoginController@logout')->name('logout');

This route will handle the logout request.

Step 2: Implement the Logout Method

In your CustomLoginController, add a method to handle the logout process:

public function logout(Request $request)
{
    Auth::logout();

    $request->session()->invalidate();

    $request->session()->regenerateToken();

    return redirect('/');
}

This method logs the user out by clearing their session and redirecting them to the homepage.

Step 3: Add a Logout Button

To trigger the logout, you can add a logout button to your application’s navigation or dashboard:

<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
    @csrf
</form>

<a href="{{ route('logout') }}"
    onclick="event.preventDefault();
             document.getElementById('logout-form').submit();">
    {{ __('Logout') }}
</a>

This button will send a POST request to the logout route when clicked, effectively logging the user out.

Step 4: Test the Logout Process

Finally, test the logout functionality by logging in as a user and then logging out using the button you just created. After logging out, you should be redirected to the homepage, and your session should be invalidated.

Creating custom login and logout functions in Laravel gives you the flexibility to tailor the authentication process to your applicationโ€™s unique requirements. Whether you need to add additional validation, use different login credentials, or implement custom security measures, Laravel provides the tools to do so efficiently.

How can I customize the default Laravel authentication?

Customizing the default Laravel authentication involves modifying the default controllers, routes, and views, or creating entirely new ones to suit your specific needs.

Is it safe to handle custom authentication without using Laravelโ€™s built-in features?

Yes, it is safe as long as you follow security best practices, such as proper data validation, password hashing, and implementing measures like CSRF protection.

What are the best practices for storing user passwords securely?

Always hash passwords using algorithms like Bcrypt or Argon2, and never store passwords in plain text.

Can I implement social media login in a custom Laravel authentication system?

Yes, you can integrate social media login by using Laravel Socialite or similar packages to handle OAuth authentication.

How do I integrate multi-factor authentication into my custom authentication system?

Multi-factor authentication can be integrated by using packages that support 2FA, or by manually implementing methods to send one-time passwords (OTPs) to users via email or SMS.

If youโ€™re planning to revamp your online presence, donโ€™t miss exploring ourย website designing servicesย and customย website developmentย solutions tailored to your business needs.

About Post Author

Kishan Kumar || Founder @ Appfinz

administrator

๐—ฆ๐—ต๐—ผ๐—ฝ๐—ถ๐—ณ๐˜† ๐—ฃ๐—น๐˜‚๐˜€ ๐—˜๐˜…๐—ฝ๐—ฒ๐—ฟ๐˜ | Digital Marketing Consultant (Organic & Paid Outreach) | Built ๐—”๐—ฝ๐—ฝ๐—ณ๐—ถ๐—ป๐˜‡ ๐—ง๐—ฒ๐—ฐ๐—ต๐—ป๐—ผ๐—น๐—ผ๐—ด๐—ถ๐—ฒ๐˜€ | Working with Graphics, Website & Performance Marketing Enthusiasts.
Ask for ๐–๐ž๐›๐ฌ๐ข๐ญ๐ž ๐ƒ๐ž๐ฏ๐ž๐ฅ๐จ๐ฉ๐ฆ๐ž๐ง๐ญ | ๐’๐จ๐œ๐ข๐š๐ฅ ๐Œ๐ž๐๐ข๐š ๐Ž๐ฎ๐ญ๐ซ๐ž๐š๐œ๐ก | ๐†๐จ๐จ๐ ๐ฅ๐ž ๐‚๐š๐ฆ๐ฉ๐š๐ข๐ ๐ง๐ฌ | ๐‹๐š๐ซ๐š๐ฏ๐ž๐ฅ & ๐’๐ก๐จ๐ฉ๐ข๐Ÿ๐ฒ ๐ƒ๐ž๐ฏ๐ž๐ฅ๐จ๐ฉ๐ฆ๐ž๐ง๐ญ

See author's posts

Tags: Laravel authentication guide, Laravel custom authentication, Laravel custom login, Laravel custom logout, Laravel session management, Laravel user authentication, secure login in Laravel

Continue Reading

Previous How to change Password in Laravel Using Tinker Method
Next Building a Simple AJAX CRUD Application in Laravel: Add, Edit, Delete, and List

Please Support us

If our blogs help you to solve your problem, you can help us running this blogs by paying for a small coffee brew.

Google Pay/Phonepe/Paytm Number: +91 8340725097

If my blogs help you to find your answer and query, then help us with above mentioned links

React JS

  • React
  • React Native

Difference Between Ionic React Vs React Native

5 years ago
  • React
  • React Native

What is the difference between React Native and React?

5 years ago

Laravel

  • Laravel
  • PHP

Building a Simple AJAX CRUD Application in Laravel: Add, Edit, Delete, and List

10 months ago
  • Laravel

Laravel Custom Authentication | Registration, Login, Logout Process | Laravel login with session

10 months ago
  • Laravel

How to change Password in Laravel Using Tinker Method

10 months ago
  • Laravel
  • PHP

User Login with API Using Laravel 11

10 months ago
  • Laravel

What’s the differences between PUT and PATCH? in laravel

11 months ago

Recent Blogs

  • Social Media

The upsurge of niche social media platforms and what that means for your brand

4 years ago
  • PHP

WordPress Hooks and Filter | Complete Overview of WordPress hooks

4 weeks ago
  • Marketing
  • SEO

What are the 7 Ps of Marketing?

8 months ago
  • PHP

What is Fetch PHP? How to use it inside PHP

8 months ago
  • Laravel
  • PHP

Building a Simple AJAX CRUD Application in Laravel: Add, Edit, Delete, and List

10 months ago
  • Laravel

Laravel Custom Authentication | Registration, Login, Logout Process | Laravel login with session

10 months ago

Appfinz Technologies

Appfinz Technologies has been in the industry for more than 12 years, holding a core motive to make a change in the world by providing solutions perfectly crafted with intelligence and creativity. the company is gradually yet constantly spreading its legs across the world leaving the rat race for the rest and striving to become better than the best!

Our services

  • Shopify Development Company
  • SEO Services In India
  • SEO Packages
  • Digital Marketing Packages
  • Social Media Marketing

Categories

Angular JS Artificial Intelligence Ionic Framework Javascript Jquery Laravel Marketing Node JS Payment Gateway PHP Python React React Native SEO Shopify Social Media VPN Vue JS Website Trends Wordpress
  • Home
  • Instagram
  • Facebook
  • Twitter
  • Linkedin
  • Github
ยฉ Appfinz Technologies | All rights reserved.