Latest

latest

How to register and login a user using Ajax in Laravel

Monday 15 January 2018

/ by Fx
Today, I will share with you how to use  ajax to register a user in laravel using bootstrap modal. The error displayed will be shown on the bootstrap modal.

I assume you are a bit familiar with Laravel simple validation on post request  which provides basic validation and return errors when the rules are not met. This tutorial will show you how to configure laravel  validation in a bootstrap pop up modal without page refresh, and how to login the user if the validation is successful.  It is little bit hard for new laracasts but the steps are easy if well understood.
I will take it step by step, as I illustrate with the following code snippets ;
  1. Create a new laravel project using the laravel new blog command
  2. Open resources/views/layouts/app.blade.php file and add this bootstrap model link on it.
<li> <a href="#" data-toggle="modal" data-target="#SignUp">Register</a> </li>

3.Create a form in a Modal as shown:




 <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h3 class="modal-title text-center primecolor">Sign Up</h3>
            </div>
            <div class="modal-body" style="overflow: hidden;">
                <div id="success-msg" class="hide">
                    <div class="alert alert-info alert-dismissible fade in" role="alert">
                      <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">×</span>
                      </button>
                      <strong>Success!</strong> Check your mail for login confirmation!!
                    </div>
                </div>
                <div class="col-md-offset-1 col-md-10">
                    <form method="POST" id="Register">
                        {{ csrf_field() }}
                        <div class="form-group has-feedback">
                            <input type="text" name="name" value="{{ old('name') }}" class="form-control" placeholder="Full name">
                            <span class="glyphicon glyphicon-user form-control-feedback"></span>
                            <span class="text-danger">
                                <strong id="name-error"></strong>
                            </span>
                        </div>
                        <div class="form-group has-feedback">
                            <input type="email" name="email" value="{{ old('email') }}" class="form-control" placeholder="Email">
                            <span class="glyphicon glyphicon-envelope form-control-feedback"></span>
                            <span class="text-danger">
                                <strong id="email-error"></strong>
                            </span>
                        </div>
                        <div class="form-group has-feedback">
                            <input type="password" name="password" class="form-control" placeholder="Password">
                            <span class="glyphicon glyphicon-lock form-control-feedback"></span>
                            <span class="text-danger">
                                <strong id="password-error"></strong>
                            </span>
                        </div>
                        <div class="form-group has-feedback">
                            <input type="password" name="password_confirmation" class="form-control" placeholder="Retype password">
                            <span class="glyphicon glyphicon-log-in form-control-feedback"></span>
                        </div>
                        <div class="row">
                            <div class="col-xs-12 text-center">
                              <button type="button" id="submitForm" class="btn btn-primary btn-prime white btn-flat">Register</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
4.Open the Script tag <script></script> and write your Ajax Codes as follows:


    
$('body').on('click', '#submitForm', function () {
            var registerForm = $("#Register");
            var formData = registerForm.serialize();
     console.log(formData);
    //hide all the errors
    $('#email-error').html('');
    $('#name-error').html('');
    $('#password-error').html('');

    //make the ajax request
    $.ajax(
        {
            url:'/register',
            type:'post',
            data:formData,

            success:function(data){
                console.log(data);
                  if (data.errors) {
                      if (data.errors.name) {
                          $('#name-error').html(data.errors.name[0]);
                      }
                      if (data.errors.email) {
                          $('#email-error').html(data.errors.email[0]);
                      }
                      if (data.errors.password) {
                          $('#password-error').html(data.errors.password[0]);
                      }

                  }
                  if (data.success) {

                    console.log('user created');
                      $('#success-msg').removeClass('hide');
                      setInterval(function () {
                          $('#SignUp').modal('hide');
                          $('#success-msg').addClass('hide');
                      }, 3000);
                  }
            },

        });
});


5. Open your register controller,and overwrite the default laravel controller as follows:



Thanks for reading, share and comment on this tutorial.

<?php

namespace App\Http\Controllers\Auth;

use App\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Response;
use Auth;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
     public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
        ]);

        $input = $request->all();

        if ($validator->passes()) {

            // Store your user in database 
            $user = User::create([
            'name' => $request['name'],
            'email' => $request['email'],
            'phone' => 2,
            'usertype'=>45,
            'password' => bcrypt($request['password']),

        ]);
             Auth::login($user);

            return Response::json(['success' => '1']);

        }
        
        return Response::json(['errors' => $validator->errors()]);
    }

    // /**
    //  * Create a new user instance after a valid registration.
    //  *
    //  * @param  array  $data
    //  * @return \App\User
    //  */
    // protected function create(array $data)
    // {
    //     return User::create([
    //         'name' => $data['name'],
    //         'email' => $data['email'],
    //         'phone' => $data['phone'],
    //         'usertype'=>$data['usertype'],
    //         'password' => bcrypt($data['password']),
    //     ]);
    // }
}

No comments

Post a Comment

Comment, and tell people what you think

Don't Miss
© all rights reserved
made with by xclusivefx