Laravel Bootstrap Modal Form Validation

To create a bootstrap modal form validation in Laravel, use the simple Ajax form validation using a bootstrap modal. The server checks all the input fields against specified validation, and if any of the validation breaks, it will redirect to our create page with error messages.

Here are the steps to use bootstrap modal form validation in Laravel:

Step 1: Configure Laravel Project.

Install the new Laravel project by typing the following command.

composer create-project --prefer-dist laravel/laravel championsleaguegoalscorer

Step 2: Set up a MySQL database in .env file.

Configure the database in the .env file.

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

I have set up local database credentials.

Next, migrate two tables provided by Laravel. Switch to your terminal and hit the following command.

php artisan migrate 

It will create 2(two) tables in your database.

  1. users
  2. password_resets

Step 3: Build a model, migration file, and controller for our Goalscorer table.

Hit the following command in your terminal.

php artisan make:model Goalscorer -m 

It will create two files.

  1. Goalscorer.php model.
  2. create_goalscorers_table migration file.

We need to create Schema for the goalscorers table. So navigate to Laravel  >>  database  >>  migrations  >>  create_goalscorers_table.

// create_goalscorers_table
/**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('goalscorers', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('club');
            $table->string('country');
            $table->integer('score');
            $table->timestamps();
        });
    }

Now, migrate the table to the database.

php artisan migrate 

In the database, you can see the goalscorers table.

Step 4: Construct a view file to add the Scorer Detail to the database.

Create a file in the resources  >>  views  >>   create.blade.php and add the following code.

<!-- create.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="_token" content="{{csrf_token()}}" />
    <title>Champion League Goalscorer</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.3/css/bootstrap.css" rel="stylesheet">  
      <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.3/js/bootstrap.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.js"></script> 
  </head>
  <body>

  	<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" id="open">Open Modal</button>
	<form method="post" action="{{url('chempionleague')}}" id="form">
		@csrf
  <!-- Modal -->
  <div class="modal" tabindex="-1" role="dialog" id="myModal">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
    	<div class="alert alert-danger" style="display:none"></div>
      <div class="modal-header">
      	
        <h5 class="modal-title">Uefa Champion League</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="row">
            <div class="form-group col-md-4">
              <label for="Name">Name:</label>
              <input type="text" class="form-control" name="name" id="name">
            </div>
          </div>
          <div class="row">
              <div class="form-group col-md-4">
                <label for="Club">Club:</label>
                <input type="text" class="form-control" name="club" id="club">
              </div>
          </div>
          <div class="row">
             <div class="form-group col-md-4">
                <label for="Country">Country:</label>
                <input type="text" class="form-control" name="country" id="country">
              </div>
          </div>
          <div class="row">
            <div class="form-group col-md-4">
              <label for="Goal Score">Goal Score:</label>
              <input type="text" class="form-control" name="score" id="score">
            </div>
          </div>
      </div>
      <div class="modal-footer">
      	<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button  class="btn btn-success" id="ajaxSubmit">Save changes</button>
        </div>
    </div>
  </div>
</div>
  </form>
</div>
</body>
</html>

Step 5: Add jQuery code.

Include jQuery.ajax() function to submit the request to the server in that click event.

<script src="http://code.jquery.com/jquery-3.3.1.min.js"
               integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
               crossorigin="anonymous">
      </script>
      <!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
      <script>
         jQuery(document).ready(function(){
            jQuery('#ajaxSubmit').click(function(e){
               e.preventDefault();
               $.ajaxSetup({
                  headers: {
                      'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                  }
              });
               jQuery.ajax({
                  url: "{{ url('/chempionleague') }}",
                  method: 'post',
                  data: {
                     name: jQuery('#name').val(),
                     club: jQuery('#club').val(),
                     country: jQuery('#country').val(),
                     score: jQuery('#score').val(),
                  },
                  success: function(result){
                  	if(result.errors)
                  	{
                  		jQuery('.alert-danger').html('');

                  		jQuery.each(result.errors, function(key, value){
                  			jQuery('.alert-danger').show();
                  			jQuery('.alert-danger').append('<li>'+value+'</li>');
                  		});
                  	}
                  	else
                  	{
                  		jQuery('.alert-danger').hide();
                  		$('#open').hide();
                  		$('#myModal').modal('hide');
                  	}
                  }});
               });
            });
      </script>

The final code of create.blade.php looks like below.

<!-- create.blade.php -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="_token" content="{{csrf_token()}}" />
    <title>Champion League Goalscorer</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.3/css/bootstrap.css" rel="stylesheet">  
      <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.3/js/bootstrap.min.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.js"></script> 
  </head>
  <body>

  	<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" id="open">Open Modal</button>
	<form method="post" action="{{url('chempionleague')}}" id="form">
		@csrf
  <!-- Modal -->
  <div class="modal" tabindex="-1" role="dialog" id="myModal">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
    	<div class="alert alert-danger" style="display:none"></div>
      <div class="modal-header">
      	
        <h5 class="modal-title">Uefa Champion League</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="row">
            <div class="form-group col-md-4">
              <label for="Name">Name:</label>
              <input type="text" class="form-control" name="name" id="name">
            </div>
          </div>
          <div class="row">
              <div class="form-group col-md-4">
                <label for="Club">Club:</label>
                <input type="text" class="form-control" name="club" id="club">
              </div>
          </div>
          <div class="row">
             <div class="form-group col-md-4">
                <label for="Country">Country:</label>
                <input type="text" class="form-control" name="country" id="country">
              </div>
          </div>
          <div class="row">
            <div class="form-group col-md-4">
              <label for="Goal Score">Goal Score:</label>
              <input type="text" class="form-control" name="score" id="score">
            </div>
          </div>
      </div>
      <div class="modal-footer">
      	<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button  class="btn btn-success" id="ajaxSubmit">Save changes</button>
        </div>
    </div>
  </div>
</div>
  </form>
</div>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"
               integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
               crossorigin="anonymous">
      </script>
      <!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
      <script>
         jQuery(document).ready(function(){
            jQuery('#ajaxSubmit').click(function(e){
               e.preventDefault();
               $.ajaxSetup({
                  headers: {
                      'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                  }
              });
               jQuery.ajax({
                  url: "{{ url('/chempionleague') }}",
                  method: 'post',
                  data: {
                     name: jQuery('#name').val(),
                     club: jQuery('#club').val(),
                     country: jQuery('#country').val(),
                     score: jQuery('#score').val(),
                  },
                  success: function(result){
                  	if(result.errors)
                  	{
                  		jQuery('.alert-danger').html('');

                  		jQuery.each(result.errors, function(key, value){
                  			jQuery('.alert-danger').show();
                  			jQuery('.alert-danger').append('<li>'+value+'</li>');
                  		});
                  	}
                  	else
                  	{
                  		jQuery('.alert-danger').hide();
                  		$('#open').hide();
                  		$('#myModal').modal('hide');
                  	}
                  }});
               });
            });
      </script>


</body>
</html>

Laravel Modal Bootstrap Tutorial

Step 6: Create one controller and route 

php artisan make:controller GoalscorerController --resource 

It will create one controller file called GoalscorerController.php.

We register one route in routes  >>  web.php file. So let us do it.

// web.php

Route::resource('chempionleague','GoalscorerController');

Now, shift to your terminal and type the next command.

php artisan route:list

The next step would be to go to the GoalscorerController.php file and add some code to the create () function.

// GoalscorerController.php

  /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('create');
    }

After starting the Laravel Development server, go to the terminal and follow the following command.

php artisan serve 

Transfer to the browser and hit this URL: http://localhost:8000/chempionleague/create

Step 7: Write the store function to store the data

We require coding the store function in sequence to store the data in the database.

//GoalscorerController.php
/**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

         $validator = \Validator::make($request->all(), [
            'name' => 'required',
            'club' => 'required',
            'country' => 'required',
            'score' => 'required',
        ]);
        
        if ($validator->fails())
        {
            return response()->json(['errors'=>$validator->errors()->all()]);
        }
        $goalscorer= new Goalscorer();
        $goalscorer->name=$request->get('name');
        $goalscorer->club=$request->get('club');
        $goalscorer->country=$request->get('country');
        $goalscorer->score=$request->get('score');
        $goalscorer->save();
   
        return response()->json(['success'=>'Data is successfully added']);
    }

Step 8: Display Error

If you press the submit button and all fields are blank, the validator fails and displays errors.

Laravel Bootstrap Tutorial

That’s it.

7 thoughts on “Laravel Bootstrap Modal Form Validation”

  1. I did all the steps above but it errors as follows:

    Uncaught TypeError: Cannot read property ‘fn’ of undefined
    at util.js:70
    at util.js:10
    at bootstrap.min.js:6
    at bootstrap.min.js:6
    (anonymous) @ util.js:70
    (anonymous) @ util.js:10
    (anonymous) @ bootstrap.min.js:6
    (anonymous) @ bootstrap.min.js:6

    3jquery-3.3.1.min.js:2
    POST http://127.0.0.1:8000/chempionleague 500 (Internal Server Error)
    send @ jquery-3.3.1.min.js:2
    ajax @ jquery-3.3.1.min.js:2
    (anonymous) @ create:81
    dispatch @ jquery-3.3.1.min.js:2
    y.handle @ jquery-3.3.1.min.js:2

    Can you help me? Please.

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.