article

Friday, May 20, 2022

Laravel 9 Custom Login Form with Jquery Ajax

Laravel 9 Custom Login Form with Jquery Ajax

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

Connecting our Database

open .env file root directory.

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

Database Migration
php artisan migrate

C:\xampp\htdocs\laravel9\blog>php artisan migrate
Migration table created successfully.
check database table

make a new user from tinker and test using it and run the command

php artisan tinker
C:\xampp\htdocs\laravel9\blog>php artisan tinker

write this code

User::create(['name' => 'cairocoders', 'email' => 'cairocoders@gmail.com', 'password' => Bcrypt('123456')])

check database table users new user added

Creating Controller

php artisan make:controller UserController
C:\xampp\htdocs\laravel9\blog>php artisan make:controller UserController
change it with the following codes:

blog\app\Http\Controllers\UserController.php
//blog\app\Http\Controllers\UserController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;

class UserController extends Controller
{
    public function index()
    {
        return view('login');
    }
       
    public function check(Request $request)
    {  
        $user = $request->username;
        $pass  = $request->password;

        if (auth()->attempt(array('name' => $user, 'password' => $pass)))
        {
            return response()->json([ [1] ]);
        } 
        else
         {  
            return response()->json([ [3] ]);
         }  
    }

    public function home()
    {
        return view('home');
    }
   
    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->flush();
        return redirect('/');
    }
}
Create Views
blog\resources\views\login.blade.php
//blog\resources\views\login.blade.php
<html>
<head>
<title>Laravel 9 Custom Login Form with Jquery Ajax</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
<style type="text/css">
body {
  margin: 0;
  padding: 0;
  background-color: #17a2b8;
  height: 100vh;
}
#login .container #login-row #login-column #login-box {
  margin-top: 90px;
  max-width: 600px;
  height: 320px;
  border: 1px solid #9C9C9C;
  background-color: #EAEAEA;
}
#login .container #login-row #login-column #login-box #frm_login {
  padding: 20px;
}
.has-error {
    border: 1px solid red;
}
</style>
</head>
<body>
    <div id="login">
        <h3 class="text-center text-white pt-5">Laravel 9 Custom Login Form with Jquery Ajax</h3>
        <div class="container">
            <div id="login-row" class="row justify-content-center align-items-center">
                <div id="login-column" class="col-md-6">
                    <div id="login-box" class="col-md-12">
                        <form name="frm_login" class="form" id="frm_login">    
							@csrf
                            <h3 class="text-center text-info">Login</h3>
                            <div class="mb-3">
                                <label for="username" class="text-info">Username:</label>
                                <input type="text" class="form-control" size="10px" id="username" name="username">
                            </div>
                            <div class="mb-3">
                                <label for="password" class="text-info">Password:</label>
                                <input type="password" class="form-control" size="10px" id="password" name="password">
                            </div>
                            <div class="mb-3">
                                <button type="button" class="btn btn-primary" onclick="login()">Sign In</button>
                            </div>
                            <div id="err" style="color: red"></div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script>
    function login()
    { 
        if($('#username').val() == "")
        { 
            $('#username').addClass('has-error');
            return false;
        }
        else if($('#password').val() == "")
        {
            $('#password').addClass('has-error');
            return false;
        }
        else {
            var data = $("#frm_login").serialize();

            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            $.ajax({
                type : 'POST',
                url: '/check',
                data : data,
                success : function(response)
                {
                    console.log(response); 
                    if(response == 1)
                    {
                        window.location.replace('/home');
                    }
                    else if(response == 3)
                    {
                        $("#err").hide().html("Username or Password  Incorrect. Please Check").fadeIn('slow');
                    }
                }
            });
        }
    }
</script>
</body>
</html>
blog\resources\views\home.blade.php
//blog\resources\views\home.blade.php
<h1>welcome<h1>
<h1>  {{ auth()->user()->name }}<h1>
<p><a href="/logout">Logout</a></p>
Creating Routes blog\routes\web.php
//blog\routes\web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController; //add UserController

//Route::get('/', function () {
//    return view('welcome');
//});

Route::get('/', [UserController::class, 'index']);
Route::post('/check', [UserController::class, 'check']);
Route::get('/home', [UserController::class, 'home']);
Route::get('/logout', [UserController::class, 'logout']);
Run C:\xampp\htdocs\laravel\blog>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Related Post