Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
Laravel ajax login and register

Laravel ajax login and registration with example

Aman Jain, December 4, 2021November 12, 2023

In Laravel 8 there is multiple ways to implement the laravel Ajax login and registration like Laravel provides its own auth with packages Jetstream, passport,sanctum, breeze and fortify. These all packages are easy to install and configure but sometimes our application requirement and design patterns are different or we can say we want fully customized solution. Therefore we have already covered simple login and registration in out last article and today i am going to share login and registration using Ajax.

For this tutorial we will use jQuery for Ajax request and form validation. Bootstrap for better ui experience.

Step to Laravel ajax login and registration with example

Let’s begin the tutorial of custom login and registration step by step

Step 1: Create a laravel project

First step is to create the Laravel 8 project using composer command or you can also read the How to install laravel 8 ? and Laravel artisan command to generate controllers, Model, Components and Migrations

composer create-project laravel/laravel example-app

Step 2: Configure database and table

Next step is to configure the database for our project, table and data. I assuming you have created the database using MySQL command line or phpMyAdmin then open .env or if file not exist then rename .env.example file to .env file in root folder and change database details accordingly.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=password

Next, Laravel comes with default users, reset password etc migration and user model. Thus run the artisan command to create the user table in database using below command in command line(root directory of project)

php artisan migrate

Step 3: Create a Controller

Now, Create a controller manually in app\Http\Controllers or create using artisan command

php artisan make:controller AuthController

Above command will create a controller in app\Http\Controllers\AuthController.php and now open the controller and replace code.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Models\User;

class AuthController extends Controller
{
    function loginView()
    {
        return view("login");
    }

    function registerView()
    {
        return view("register");
    }

    function doLogin(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'email' => 'required|email',   // required and email format validation
            'password' => 'required', // required and number field validation

        ]); // create the validations
        if ($validator->fails())   //check all validations are fine, if not then redirect and show error messages
        {
            return response()->json($validator->errors(),422);  
            // validation failed return with 422 status

        } else {
            //validations are passed try login using laravel auth attemp
            if (\Auth::attempt($request->only(["email", "password"]))) {
                return response()->json(["status"=>true,"redirect_location"=>url("dashboard")]);
                
            } else {
                return response()->json([["Invalid credentials"]],422);
                
            }
        }
    }

    function doRegister(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'email' => 'required|email|unique:users,email',   // required and email format validation
            'password' => 'required|min:8', // required and number field validation
            'confirm_password' => 'required|same:password',

        ]); // create the validations
        if ($validator->fails())   //check all validations are fine, if not then redirect and show error messages
        {
            return response()->json($validator->errors(),422);  
            // validation failed return back to form

        } else {
            //validations are passed, save new user in database
            $User = new User;
            $User->name = $request->name;
            $User->email = $request->email;
            $User->password = bcrypt($request->password);
            $User->save();
            
            return response()->json(["status"=>true,"msg"=>"You have successfully registered, Login to access your dashboard","redirect_location"=>url("login")]);  
           
        }
    }
   // show dashboard
    function dashboard()
    {
        return view("dashboard");
    }

    // logout method to clear the sesson of logged in user
    function logout()
    {
        \Auth::logout();
        return redirect("login")->with('success', 'Logout successfully');;
    }
}

Here we have used Illuminate\Support\Facades\Validator to validate the input fields, Auth class to authenticate user in Laravel.

we created method loginView to show login page, registerView to show register page, doLogin to handle the login submit and create the session of user using Auth::attemp() and here the which is noticeable is we have change the response()->json(), doRegister method to register a new user after submitting the register form and same as doLogin we also used json response here, dashboard to show dashboard page after login and logout to destroy the session.

There is no need to set session manually in Laravel, Laravel creates own session using Auth::attemp() method and we can get current logged in user using \Auth::user().

Step 4: Create views

We have created logic for login and register, now its time to create our view to show the form of login , register and dashboard thus here is the view

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Readerstacks laravel 8 Custom login and registration </title>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
  <link href="//netdna.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
  <script type="text/javascript" src="index.js"></script>
  <style>
    .error {
      color: red
    }
  </style>
</head>

<body class="antialiased">
  <div class="container">
    <!-- main app container -->
    <div class="readersack">
      <div class="container">
        <div class="row">
          <div class="col-md-6 offset-md-3">
            <h3>laravel 8 ajax Login - Readerstacks</h3>

            <div id="errors-list"></div>
            <form method="post" id="handleAjax" action="{{url('do-login')}}" name="postform">
              <div class="form-group">
                <label>Email</label>
                <input type="email" name="email" value="{{old('email')}}" class="form-control" />
             @csrf
              </div>
              <div class="form-group">
                <label>Password</label>
                <input type="password" name="password" class="form-control" />
              </div>
              <div class="form-group">
                <button type="submit" class="btn btn-primary">LOGIN</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
    <!-- credits -->
    <div class="text-center">
      <p>
        <a href="#" target="_top">laravel 8 ajax login and registration </a>
      </p>
      <p>
        <a href="https://readerstacks.com" target="_top">readerstacks.com</a>
      </p>
    </div>
  </div>

 
</body>

</html>

Here we used id='handleAjax' and to handle it in javascript

 <script>
    $(function() {
    // handle submit event of form
      $(document).on("submit", "#handleAjax", function() {
        var e = this;
        // change login button text before ajax
        $(this).find("[type='submit']").html("LOGIN...");

        $.post($(this).attr('action'), $(this).serialize(), function(data) {

          $(e).find("[type='submit']").html("LOGIN");
          if (data.status) { // If success then redirect to login url
            window.location = data.redirect_location;
          }
        }).fail(function(response) {
            // handle error and show in html
          $(e).find("[type='submit']").html("LOGIN");
          $(".alert").remove();
          var erroJson = JSON.parse(response.responseText);
          for (var err in erroJson) {
            for (var errstr of erroJson[err])
              $("#errors-list").append("<div class='alert alert-danger'>" + errstr + "</div>");
          }

        });
        return false;
      });
    });
  </script>

In above code we bind submit event and then sending Ajax request to laravel.

In the register form we have used $errors->any() to show form errors and then login view

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Readerstacks laravel 8 ajax login and registration </title>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
  <link href="//netdna.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
  <script type="text/javascript" src="index.js"></script>
  <style>
    .error {
      color: red
    }
  </style>
</head>
<body class="antialiased">
  <div class="container">
    <!-- main app container -->
    <div class="readersack">
      <div class="container">
        <div class="row">
          <div class="col-md-6 offset-md-3">
            <h3>laravel 8 ajax registration - Readerstacks</h3>

            
            <form method="post" id="handleRegisterAjax" action="{{url('do-register')}}" name="postform">
              <div class="form-group">
                <label>Name</label>
                <input type="text" name="name" value="{{old('name')}}" class="form-control" />
              </div>
              <div class="form-group">
                <label>Email</label>
                <input type="email" name="email" value="{{old('email')}}" class="form-control" />
                @csrf
              </div>
              <div class="form-group">
                <label>Password</label>
                <input type="password" name="password" class="form-control" />
              </div>
              <div class="form-group">
                <label>Confirm Password</label>
                <input type="password" name="confirm_password" class="form-control" />
              </div>
            <div class="form-group">
                <button type="submit" class="btn btn-primary">REGISTER</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
    <!-- credits -->
    <div class="text-center">
      <p>
        <a href="#" target="_top">laravel 8 ajax login and registration </a>
      </p>
      <p>
        <a href="https://readerstacks.com" target="_top">readerstacks.com</a>
      </p>
    </div>
  </div>
  <script>
    $(function(){
     
      $(document).on("submit","#handleRegisterAjax",function(){
            var e=this;
       
            $(this).find("[type='submit']").html("REGISTER...");
            $.post($(this).attr('action'),$(this).serialize(),function(data){
              
              $(e).find("[type='submit']").html("REGISTER");
              if(data.status){
                alert(data.msg)
                window.location=data.redirect_location;
              }
              

            }).fail(function(response) {
             
              $(e).find("[type='submit']").html("LOGIN");
              $(".alert").remove();
              var erroJson = JSON.parse(response.responseText);
              for (var err in erroJson) {
                for (var errstr of erroJson[err])
                $("[name='" + err + "']").after("<div class='alert alert-danger'>" + errstr + "</div>");
              }

            });
        return false;
      });

    });
  </script>
</body>

</html>

Same as login we assigned id to form and handle the event in jquery . Dashboard view

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>Readerstacks Laravel ajax login and registration </title>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
  <link href="//netdna.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
  <script type="text/javascript" src="index.js"></script>
  <style>
    .error {
      color: red !important
    }
    .dash{
      height: 400px;
      justify-content: center;
      align-items: center;
      font-size: 20px;
      font-weight: bold;
      display: flex;
      color:green;
      flex-direction: column;

    }
  </style>
</head>

<body class="antialiased">
  <div class="container">
    <!-- main app container -->
    <div class="readersack">
      <div class="container">
        <div class="row">
          <div class="col-md-6 offset-md-3">
            <h3>laravel  ajax Login and Registration Dashboard after login   - Readerstacks</h3>
               <!-- Show any success message -->
            @if (\Session::has('success'))
                <div class="alert alert-success">
                    <ul>
                        <li>{!! \Session::get('success') !!}</li>
                    </ul>
                </div>
            @endif
          <!-- Show any success message -->

            <!-- Check user is logged in -->
            @if(\Auth::check())
              <div class='dash'>You are logged in as  : {{\Auth::user()->email}} ,  <a href="{{url('logout')}}"> Logout</a></div> 
            @else
            <div class='dash '>
              <div class='error'> You are not logged in  </div>
              <div>  <a href="{{url('login')}}">Login</a> | <a href="{{url('register')}}">Register</a> </div>
            </div>
             
            @endif
           <!-- Check user is logged in --> 
          </div>
        </div>
      </div>
    </div>
    <!-- credits -->
    <div class="text-center">
      <p>
        <a href="#" target="_top">laravel ajax login and registration  </a>
      </p>
      <p>
        <a href="https://readerstacks.com" target="_top">readerstacks.com</a>
      </p>
    </div>
  </div>
    
</body>
</html>

As we mentioned above we can check user logged in status using \Auth::check and \Auth::user() to get current logged in user.

Step 5: Create routes

Now, create the routes for all pages and method in routes\web.php

<?php

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

Route::get('/login', [AuthController::class,"loginView"]);
Route::get('/register', [AuthController::class,"registerView"]);
Route::post('/do-login', [AuthController::class,"doLogin"]);
Route::post('/do-register', [AuthController::class,"doRegister"]);
Route::get('/dashboard', [AuthController::class,"dashboard"]);
Route::get('/logout', [AuthController::class,"logout"]);

Now start the application using php artisan serve then you can access the URLs.

Screenshot 2021 12 04 at 5.01.54 PM
Screenshot 2021 12 04 at 5.02.10 PM
Screenshot 2021 12 04 at 5.02.18 PM
bf262d9c 04ac 43e0 8aea f2be8cbb5add
f59b4dd0 83b7 4665 b1fc 0ddf30c2274a
Laravel Ajax login and register form

Related

Php Laravel ajaxlaravelloginphpregister

Post navigation

Previous post
Next post

Related Posts

Php How to use limit query in Laravel Eloquent

How to use limit query in Laravel eloquent query with example

February 5, 2022October 4, 2022

Limit clause is used to restrict the number of rows return in executed query. It’s quite useful when working with large data set since querying the large data creates performance issues so to overcome with the large dataset issue we use limit clause in a query. Laravel Limit clause accepts…

Read More
Php How to Concat Two Columns in Laravel Eloquent Query With Search

How to Concat Two Columns in Laravel Eloquent Query With Search ?

June 22, 2022June 22, 2022

In this article we will learn to use aggregate function concat in laravel eloquent with search and query builder. Concat is used to join two columns and in laravel eloquent there is no method for concat but we can use DB builder to use native MySQL Methods. In MySQL or…

Read More
Php Use Soft Delete to Temporary (Trash) Delete the Records in Laravel

Use Soft Delete to Temporary (Trash) Delete the Records in Laravel 9 ?

June 14, 2022June 14, 2022

Soft delete in laravel is use to hide the record from users by keeping the data in the database. In laravel we use Soft Delete to Temporary (Trash) Delete the Records. There is many purpose of soft delete like deleting the user for admin but keep all the information in…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version