Laravel Validation In Bootstrap Model Using Ajax

Today, Laravelcode share with you how to laravel validation handle in bootstrap popup using ajax. you have many time required this type functionality in your laravel aplication. so, we are write this tutorial for it how to dispan laravel validation error in bootstrap popoup or model.

We all are very familiar with laravel simple validation on post request and handale all validation error after any validatioon false it is vary easy and very simple. but manage laravel validation in popoup or model without page refresh is little bit hard for new commer in laravel.

When you use bootstrap model and popup for register form or any type of form that time you fill all the fields and click on submit button then if any validation false then how to handale in model without closing model when validation make false.

We are use laravel register form for this tutorials. we are open laravel register form open in bootstrap model and then manage registration form validation in bootstrap popup or model.

We are make some very easy code for it simple follow this step.

model-validation

Step : 1 Open Boostrap Model On Register Menu Link

If youe have create laravel new project then open resources/views/layouts/app.blade.php file and add bootstrap model link on it.


<li>
    <a href="#" data-toggle="modal" data-target="#SignUp">Register</a>
</li>

Add model link on register menu then create model

Step : 2 Create Form In Model

Now, we are create register form into bootstrap model when user click on register menu then open register form on model and here we are manage laravel validation if any validation false then it diplay into the model.


<div id="SignUp" class="modal fade" role="dialog">
    <div class="modal-dialog">

    <!-- Modal content-->
        <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>

    </div>
</div>

After done write register model code then write jquery ajax code for form submit

Step : 3 jQuery Ajax Code For Form Submit

We are open laravel register form in bootstrap model then we are write here form submit code into jquery ajax. simple copy followign code and past into script tag.


<script type="text/javascript">
    $('body').on('click', '#submitForm', function(){
        var registerForm = $("#Register");
        var formData = registerForm.serialize();
        $( '#name-error' ).html( "" );
        $( '#email-error' ).html( "" );
        $( '#password-error' ).html( "" );

        $.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) {
                    $('#success-msg').removeClass('hide');
                    setInterval(function(){ 
                        $('#SignUp').modal('hide');
                        $('#success-msg').addClass('hide');
                    }, 3000);
                }
            },
        });
    });
</script>

Step : 4 Overwrite register function

Now, last and final step is overwrite your RegisterController.php's register function. so open your app/Http/Controllers/Auth/RegisterController.php file and put into it following code.


namespace App\Http\Controllers\Auth;

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

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');
    }

    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 

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

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

Now we are ready to run our example so run bellow command ro quick run:


php artisan serve

Now you can open bellow URL on your browser:


http://localhost:8000

If you face any problem then please write a comment or give some suggestions for improvement. Thanks...

 Prev post

Next post