Sample App Register Laravel with Ajax

    

Sample App Register Laravel with Ajax

Hello dear,

This tutorial will give you an example of how to clone a Laravel project from Gitlab. let’s discuss the steps to clone the Laravel project from GitHub. I explained simply about the clone Laravel project from GitHub. This article goes into detail on the clone Laravel project from Github on the server.

In this tutorial, I will show you step-by-step how to clone Laravel projects from Github, GitLab, or Bitbucket and set up an Ubuntu server from scratch. you can easily clone Laravel 6, Laravel 7, Laravel 8, Laravel 9, and Laravel 10 projects from this post.

So, let's follow the below step-by-step and get done with the clone Laravel app.





Route

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/


/** for side bar menu active */
function set_active( $route ) {
    if( is_array( $route ) ){
        return in_array(Request::path(), $route) ? 'active' : '';
    }
    return Request::path() == $route ? 'active' : '';
}

Route::get('/', function () {
    return view('auth.login');
});

Route::group(['middleware'=>'auth'],function()
{
    Route::get('home',function()
    {
        return view('home');
    });
    Route::get('home',function()
    {
        return view('home');
    });
});

Auth::routes();
Route::group(['namespace' => 'App\Http\Controllers\Auth'],function()
{
    // ----------------------------login ------------------------------//
    Route::controller(LoginController::class)->group(function () {
        Route::get('login', 'login')->name('login');
        Route::post('login/push', 'authenticate')->name('login/push');
        Route::get('/logout', 'logout')->name('logout');
        Route::post('change/password', 'changePassword')->name('change/password');
    });
    // ------------------------ register sccount ----------------------//
     Route::controller(RegisterController::class)->group(function () {
        Route::get('register/form', 'index')->name('register/form');
        Route::post('register/save','saveRecord')->name('register/save');    
    });

    // -------------------------- forgot password ---------------------//
    Route::controller(ForgotPasswordController::class)->group(function () {
        Route::get('/forgot/password','sendEmail')->name('forgot/password');    
    });
});

Route::group(['namespace' => 'App\Http\Controllers'],function()
{
    // -------------------------- main dashboard ----------------------//
    Route::controller(HomeController::class)->group(function () {
        Route::get('/home', 'index')->middleware('auth')->name('home');

    });
});

RegisterController

app/Http/Controllers/Auth/RegisterController.php

<?php

namespace App\Http\Controllers\Auth;

use DB;
use Hash;
use Carbon\Carbon;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\Password;

class RegisterController extends Controller
{
    /** page register new */
    public function index()
    {
        return view('auth.register');
    }

    /** save new record */
    public function saveRecord(Request $request)
    {
        try {

            $dt        = Carbon::now();
            $todayDate = $dt->toDayDateTimeString();

            User::create([
                'name'      => $request->first_name .$request->last_name,
                'avatar'    => $request->image,
                'email'     => $request->email,
                'join_date' => $todayDate,
                'role_name' => $request->role_name,
                'password'  => Hash::make($request->password),
            ]);

            $data = [];
            $data['response_code']  = '200';
            $data['status']         = 'success';
            $data['message']        = 'success Register';
            return response()->json($data);

        } catch(\Exception $e) {
            \Log::info($e);
            $data = [];
            $data['response_code']  = '400';
            $data['status']         = 'error';
            $data['message']        = 'fail Register';
            return response()->json($data);
        }
    }
}

register.blade.php

resources/views/auth/register.blade.php

@extends('layouts.app')
@section('content')
        <div class="d-flex flex-column flex-root" id="kt_app_root">
        <div class="d-flex flex-column flex-lg-row flex-column-fluid">
            <div class="d-flex flex-column flex-lg-row-auto bg-primary w-xl-600px positon-xl-relative">
                <div class="d-flex flex-column position-xl-fixed top-0 bottom-0 w-xl-600px scroll-y">
                    <div class="d-flex flex-row-fluid flex-column text-center p-5 p-lg-10 pt-lg-20">
                        <a href="{{ route('home') }}" style="padding-top: 5rem !important;padding-bottom: 2rem">
                            <img alt="Logo" src="{{ URL::to('assets/media/logos/logo.png') }}" class="theme-light-show h-70px h-lg-80px">
                        </a>
                        <h1 class="d-none d-lg-block fw-bold text-white fs-2qx pb-5 pb-md-10">
                            Welcome to Subscribers </h1>
                        <p class="d-none d-lg-block fw-semibold fs-2 text-white">
                            Plan your learn can choosing a sample creating <br>
                            an online and free soure code
                        </p>
                    </div>
                    <div class="d-none d-lg-block d-flex flex-row-auto bgi-no-repeat bgi-position-x-center bgi-size-contain bgi-position-y-bottom min-h-100px min-h-lg-350px" style="background-image: url({{ URL::to('assets/media/illustrations/dozzy-1/17.png') }})">
                    </div>
                </div>
            </div>

            <div class="d-flex flex-column flex-lg-row-fluid py-10">
                <div class="d-flex flex-center flex-column flex-column-fluid">
                    <div class="w-lg-600px p-10 p-lg-15 mx-auto">
                        <form class="form w-100" id="kt_sign_up_form" data-kt-redirect-url="/login" method="POST">
                            <div class="mb-10 text-center">
                                <h1 class="text-dark mb-3">Create an Account</h1>
                                <div class="text-gray-400 fw-semibold fs-4">
                                    Already have an account?
                                    <a href="{{ route('login') }}" class="link-primary fw-bold">
                                        Sign in here
                                    </a>
                                </div>
                            </div>
                            <button type="button" class="btn btn-light-primary fw-bold w-100 mb-10">
                                <img alt="Logo" src="{{ URL::to('assets/media/svg/brand-logos/google-icon.svg') }}" class="h-20px me-3">
                                Sign in with Google
                            </button>
                            <div class="d-flex align-items-center mb-10">
                                <div class="border-bottom border-gray-300 mw-50 w-100"></div>
                                <span class="fw-semibold text-gray-400 fs-7 mx-2">OR</span>
                                <div class="border-bottom border-gray-300 mw-50 w-100"></div>
                            </div>
                            <div class="row fv-row mb-7">
                                <div class="col-xl-6">
                                    <label class="form-label fw-bold text-dark fs-6">First Name</label>
                                    <input class="form-control form-control-lg form-control-solid" type="text" placeholder="Enter first name" id="first_name" name="first_name" autocomplete="off">
                                </div>
                                <div class="col-xl-6">
                                    <label class="form-label fw-bold text-dark fs-6">Last Name</label>
                                    <input class="form-control form-control-lg form-control-solid" type="text" placeholder="Enter last name" name="last_name" autocomplete="off">
                                </div>
                            </div>
                            <div class="fv-row mb-7">
                                <label class="form-label fw-bold text-dark fs-6">Email</label>
                                <input class="form-control form-control-lg form-control-solid" type="email" placeholder="Enter email" name="email" autocomplete="off">
                            </div>
                            <div class="fv-row mb-7" hidden>
                                <label class="form-label fw-bold text-dark fs-6">Role Name</label>
                                <input class="form-control form-control-lg form-control-solid" type="text" placeholder="Enter role name" name="role_name" autocomplete="off" value="Normal User">
                            </div>
                            <div class="fv-row mb-7" hidden>
                                <label class="form-label fw-bold text-dark fs-6">Profile</label>
                                <input class="form-control form-control-lg form-control-solid" type="text" placeholder="Enter photo" name="image" value="logo.png">
                            </div>
                            <div class="mb-10 fv-row" data-kt-password-meter="true">
                                <div class="mb-1">
                                    <label class="form-label fw-bold text-dark fs-6">Password</label>
                                    <div class="position-relative mb-3">
                                        <input class="form-control form-control-lg form-control-solid" type="password" placeholder="Enter password" name="password" autocomplete="off">
                                        <span
                                            class="btn btn-sm btn-icon position-absolute translate-middle top-50 end-0 me-n2"
                                            data-kt-password-meter-control="visibility">
                                            <i class="ki-duotone ki-eye-slash fs-2"></i> <i
                                                class="ki-duotone ki-eye fs-2 d-none"></i> </span>
                                    </div>
                                    <div class="d-flex align-items-center mb-3"
                                        data-kt-password-meter-control="highlight">
                                        <div class="flex-grow-1 bg-secondary bg-active-success rounded h-5px me-2">
                                        </div>
                                        <div class="flex-grow-1 bg-secondary bg-active-success rounded h-5px me-2">
                                        </div>
                                        <div class="flex-grow-1 bg-secondary bg-active-success rounded h-5px me-2">
                                        </div>
                                        <div class="flex-grow-1 bg-secondary bg-active-success rounded h-5px"></div>
                                    </div>
                                </div>
                                <div class="text-muted">
                                    Use 8 or more characters with a mix of letters, numbers & symbols.
                                </div>
                            </div>
                            <div class="fv-row mb-5">
                                <label class="form-label fw-bold text-dark fs-6">Confirm Password</label>
                                <input class="form-control form-control-lg form-control-solid" type="password"placeholder="Enter confirm password" name="confirm_password" autocomplete="off">
                            </div>
                            <div class="fv-row mb-10">
                                <label class="form-check form-check-custom form-check-solid form-check-inline">
                                    <input class="form-check-input" type="checkbox" name="toc" value="1">
                                    <span class="form-check-label fw-semibold text-gray-700 fs-6">
                                        I Agree <a href="#" class="ms-1 link-primary">Terms and conditions.</a>
                                    </span>
                                </label>
                            </div>
                            <div class="text-center">
                                <button type="button" id="kt_sign_up_submit" class="btn btn-lg btn-primary">
                                    <span class="indicator-label">Submit</span>
                                    <span class="indicator-progress">
                                        Please wait...
                                        <span class="spinner-border spinner-border-sm align-middle ms-2"></span>
                                    </span>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                <div class="d-flex flex-center flex-wrap fs-6 p-5 pb-0">
                    <div class="d-flex flex-center fw-semibold fs-6">
                        <a href="https://www.linkedin.com/in/soengsouy/" class="text-muted text-hover-primary px-2" target="_blank">About</a>
                        <a href="https://www.facebook.com/starcodekh" class="text-muted text-hover-primary px-2" target="_blank">Support</a>
                        <a href="https://souysoeng.com" class="text-muted text-hover-primary px-2" target="_blank">Website</a>
                    </div>
                </div>
            </div>
        </div>
    </div>

@section('script')

    <script type="text/javascript">
        
        // Class definition
        var KTSignupGeneral = function() {
            // Elements
            var form;
            var submitButton;
            var validator;
            var passwordMeter;

            // Handle form
            var handleForm = function(e) {
                    // Init form validation rules. For more info check the FormValidation plugin's official documentation:https://formvalidation.io/
                    validator = FormValidation.formValidation(form, {
                        fields: {
                            'first_name': {
                                validators: {
                                    notEmpty: {
                                        message: 'First Name is required'
                                    }
                                }
                            },
                            'last_name': {
                                validators: {
                                    notEmpty: {
                                        message: 'Last Name is required'
                                    }
                                }
                            },
                            'email': {
                                validators: {
                                    regexp: {
                                        regexp: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
                                        message: 'The value is not a valid email address',
                                    },
                                    notEmpty: {
                                        message: 'Email address is required'
                                    }
                                }
                            },
                            'password': {
                                validators: {
                                    notEmpty: {
                                        message: 'The password is required'
                                    },
                                    callback: {
                                        message: 'Please enter valid password',
                                        callback: function(input) {
                                            if(input.value.length > 0) {
                                                return validatePassword();
                                            }
                                        }
                                    }
                                }
                            },
                            'confirm_password': {
                                validators: {
                                    notEmpty: {
                                        message: 'The password confirmation is required'
                                    },
                                    identical: {
                                        compare: function() {
                                            return form.querySelector('[name="password"]').value;
                                        },
                                        message: 'The password and its confirm are not the same'
                                    }
                                }
                            },
                            'toc': {
                                validators: {
                                    notEmpty: {
                                        message: 'You must accept the terms and conditions'
                                    }
                                }
                            }
                        },
                        plugins: {
                            trigger: new FormValidation.plugins.Trigger({
                                event: {
                                    password: false
                                }
                            }),
                            bootstrap: new FormValidation.plugins.Bootstrap5({
                                rowSelector: '.fv-row',
                                eleInvalidClass: '', // comment to enable invalid state icons
                                eleValidClass: '' // comment to enable valid state icons
                            })
                        }
                    });

                    // Handle form submit using ajax
                    submitButton.addEventListener('click', function(e) {
                        e.preventDefault();
                        validator.revalidateField('password');
                        validator.validate().then(function(status) {
                            if(status == 'Valid') {
                                // Show loading indication
                                submitButton.setAttribute('data-kt-indicator', 'on');
                                // Disable button to avoid multiple click 
                                submitButton.disabled = true;
                                // Simulate ajax request
                                setTimeout(function() {
                                    // Hide loading indication
                                    submitButton.removeAttribute('data-kt-indicator');
                                    // Enable button
                                    submitButton.disabled = false;
                                    // Show message popup. For more info check the plugin's official documentation: https://sweetalert2.github.io/
                                    var data = $('#kt_sign_up_form').serialize();
                                    $.ajax({
                                        url: "{{ route('register/save') }}",
                                        type: 'POST',
                                        data: data,
                                        headers: {
                                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                                        },
                                        success: function(response){
                                            if(response.response_code == 200) {
                                                Swal.fire({
                                                    text: "You have successfully logged in!",
                                                    icon: "success",
                                                    buttonsStyling: false,
                                                    confirmButtonText: "Ok, got it!",
                                                    customClass: {
                                                        confirmButton: "btn btn-primary"
                                                    },
                                                }).then(function(redirect) {
                                                    var redirectUrl = form.getAttribute('data-kt-redirect-url');
                                                    if(redirectUrl) {
                                                        location.href = redirectUrl;
                                                    }
                                                });
                                            } else {
                                                Swal.fire({
                                                    text: "Sorry, looks like there are some errors detected, please try again.",
                                                    icon: "error",
                                                    buttonsStyling: false,
                                                    confirmButtonText: "Ok, got it!",
                                                    customClass: {
                                                        confirmButton: "btn btn-primary"
                                                    }
                                                });
                                            }
                                        },
                                        error: function(response){
                                            Swal.fire({
                                                text: "Sorry, looks like there are some errors detected, please try again.",
                                                icon: "error",
                                                buttonsStyling: false,
                                                confirmButtonText: "Ok, got it!",
                                                customClass: {
                                                    confirmButton: "btn btn-primary"
                                                }
                                            });
                                        }
                                    });
                                }, 1200);
                            } else {
                                // Show error popup. For more info check the plugin's official documentation: https://sweetalert2.github.io/
                                Swal.fire({
                                    text: "Sorry, looks like there are some errors detected, please try again.",
                                    icon: "error",
                                    buttonsStyling: false,
                                    confirmButtonText: "Ok, got it!",
                                    customClass: {
                                        confirmButton: "btn btn-primary"
                                    }
                                });
                            }
                        });
                    });

                    // Handle password input
                    form.querySelector('input[name="password"]').addEventListener('input', function() {
                        if(this.value.length > 0) {
                            validator.updateFieldStatus('password', 'NotValidated');
                        }
                    });
                }
                // Password input validation
            var validatePassword = function() {
                    return(passwordMeter.getScore() === 100);
                }
                // Public functions
            return {
                // Initialization
                init: function() {
                    // Elements
                    form = document.querySelector('#kt_sign_up_form');
                    submitButton = document.querySelector('#kt_sign_up_submit');
                    passwordMeter = KTPasswordMeter.getInstance(form.querySelector('[data-kt-password-meter="true"]'));
                    handleForm();
                }
            };
        }();

        // On document ready
        KTUtil.onDOMContentLoaded(function() {
            KTSignupGeneral.init();
        });
    </script>

@endsection
@endsection

Git Clone Full Project

1.Run `git clone 'link projer github'
2.Run composer update
3.Run cp .env.example .env or copy .env.example .env
4.Run php artisan key:generate
5.Run php artisan migrate
6.Run php artisan serve
7.Go to link localhost:8000

Step 1: Git Clone Laravel 10

First, clone a new Laravel app just by running the below command in your terminal.

https://gitlab.com/SoengSouy/app-sample-laravel-10.git

Step 2: Composer Update

Type the command in your terminal.

composer update

Step 3: Update Your Database Credentials

After that update your database credentials in your .env file which is located in your project root.

1. connection databases

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_db
DB_USERNAME=root
DB_PASSWORD=#your database password

Step 4: Make Migration

After adding the migration file run the migrate command.

php artisan migrate

Step 5:Run

After adding the run file now run the migrate command.

php artisan serve

Souy Soeng

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

Previous Post Next Post