DEV Community

Cover image for Laravel Custom Login Validation with Ajax
Adeyemi Adeshina
Adeyemi Adeshina

Posted on

Laravel Custom Login Validation with Ajax

Laravel is arguably the most used and popular PHP Framework for Web Artisans.

Laravel has its own in-built functionality for Auth (User Registration and Login). If you think you feel satisfied with the in-built functionality, you can make use of it and your application will work well. But, if you want to go further to have your own custom Auth function, this article is for you. Let's get started!

In this article, I will be showing you how you can write custom login form validation and authentication without reloading the browser.

STEP 1: Create Users
I want to assume you already have users created in your users database table.

STEP 2: Create Login Page
This our our short code for our login page view

<body>
<div class="col-lg-4 col-md-4">
   <form action="{{ route('login') }}" method="POST"  id="login_form" 
   class="request-form ">
    @csrf
   <h2>Login</h2>
   <div id="show_error" style="color: red"> </div>

   <div class="form-group mr-2">
      <label for="" class="label">Email</label>
      <input type="email" name="email" class="form-control" >
      <span class="text-danger error-text email_error" 
       style="color: red"></span>
   </div>

   <div class="form-group mr-2">
      <label for="" class="label">Password</label>
      <input type="password" name="password" class="form-control" 
      >
      <span class="text-danger error-text password_error" 
      style="color: red"></span>
   </div>

   <div class="form-group">
   <input type="submit" value="Login" class="btn  py-3 px-4" 
   style="background-color: #5f76e8; color:#ffffff">
   </div>
  </form>
</div>
//add javascript with ajax here
<script src="[place you jquery source here...]"></script>
<script>
        $("#login_form").submit(function(e){
         e.preventDefault();

        var all = $(this).serialize();

        $.ajax({
            url:  $(this).attr('action'),
            type: "POST",
            data: all,
            beforeSend:function(){
                $(document).find('span.error-text').text('');
            },
            //validate form with ajax. This will be communicating 
              with your LoginController
            success: function(data){
                if (data.status==0) {
                    $.each(data.error, function(prefix, val){
                        $('span.'+prefix+'_error').text(val[0]);
                    });
                }
               // redirect the user to [another page] if the 
                   login cred are correct. Remember this is 
                   communicating with the LoginController which we 
                   are yet to create
                if(data == 1){
                    window.location.replace(
                     '{{route("dashboard.index")}}'
                    );
                }else if(data == 2){
                 // Show the user authentication error if the 
                   login cred are invalid. Remember this is 
                   communicating with the LoginController which we 
                   are yet to create
                    $("#show_error").hide().html("Invalid login 
                       details");
                }

            }
            })

        });


    </script>
</body>



Enter fullscreen mode Exit fullscreen mode

Login View Sample : login.blade.php
Laravel Custom Login Page Validation with Ajax
NOTE: You can customize this to your desire

STEP 3: Create LoginController
Open your command prompt interface, cd to your project
directory and paste the below command there

php artisan make:controller LoginController

 namespace App\Http\Controllers;
 use Illuminate\Support\Facades\Auth;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Session;
 use Illuminate\Support\Facades\Validator;
   class LoginController extends Controller{
      public function login(Request $request){
        $validator = Validator::make($request->all(), [
        'email' =>    'required',
        'password' => 'required',
      ]);
       // validate all requests and it sends output to your 
          login.blade.php

       if(!$validator->passes()){
          return response()->json([
             'status'=>0, 
             'error'=>$validator->errors()->toArray()
          ]);
        }

       $user_cred = $request->only('email', 'password');
        if (Auth::attempt($user_cred)) {

             //if user is logged in and the role is user
            if(Auth()->user()->role=='user'){  
               return response()->json([ [1] ]);
            }  

        }else{
             //if user isn't logged in
                return response()->json([ [2] ]);
        }
        return redirect("/");
     }
  }
Enter fullscreen mode Exit fullscreen mode

STEP 4: Modify your route:web.php
add your controller to your web.php; as the case maybe
Route::post('/login'[App\Http\Controllers\LoginController::class, 'login'])->name('/login');

Hello friends, in this article we successfully created a login form with Laravel and AJAX without reloading the browser. I hope you enjoy it.

Oldest comments (0)