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 is the step-by-step guide:
Step 1: Configure Laravel Project
Install a new project by typing the following command.
composer create-project --prefer-dist laravel/laravel championsleaguegoalscorer
Step 2: Set up a MySQL database in a .env file
Configure the database in the .env file.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=8889 DB_DATABASE=championsleague DB_USERNAME=root DB_PASSWORD=root
I have set up local database credentials.
Step 3: Create model and migration files
Hit the following command in your terminal.
php artisan make:model Goalscorer -m
We need to create a Schema for the goalscorers table. So navigate to database >> migrations >> [timestamp].create_goalscorers_table.
//create_goalscorers_table.php 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: Create a controller and routes
php artisan make:controller GoalscorerController
Now, add the route inside the routes >> web.php file.
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\GoalscorerController; Route::get('/', function () { return view('welcome'); }); Route::get('championsleague/create', [GoalscorerController::class, 'create'])->name("championsleague.create");
Step 5: Construct a view file
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>Champions League Goalscorer</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> </head> <body> <div class="container"> <h2>Laravel 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 id="form"> <!-- 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"> <h2 class="modal-title">Uefa Champions League</h2> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</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="">Save changes</button> </div> </div> </div> </div> </form> </div> </body> </html>
To display this view file, return this view using the GoalscorerController’s create() method.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Goalscorer; class GoalscorerController extends Controller { public function create() { return view('create'); } }
Go to the command line or terminal and start the development server:
php artisan serve
Transfer to the browser and hit this URL: http://localhost:8000/chempionleague/create
Step 6: Add jQuery code
Include jQuery.ajax() function to submit the request to the server in that click event.
<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('/championsleague') }}", method: 'POST', data: { name: jQuery('#name').val(), club: jQuery('#club').val(), country: jQuery('#country').val(), score: jQuery('#score').val(), }, success: function(result){ if(result.success) { console.log(result.success) } 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(); $('#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>Champions League Goalscorer</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> </head> <body> <div class="container"> <h2>Laravel 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 id="form"> <!-- 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"> <h2 class="modal-title">Uefa Champions League</h2> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</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> 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('/championsleague') }}", method: 'POST', data: { name: jQuery('#name').val(), club: jQuery('#club').val(), country: jQuery('#country').val(), score: jQuery('#score').val(), }, success: function(result){ if(result.success) { console.log(result.success) } 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(); $('#myModal').modal('hide'); } }}); }); }); </script> </body> </html>
Step 7: Saving the data from the AJAX POST request into the database
We need to register the second route in the routes >> web.php file. So let us do it.
// web.php <?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\GoalscorerController; Route::get('/', function () { return view('welcome'); }); Route::get('championsleague/create', [GoalscorerController::class, 'create'])->name("championsleague.create"); Route::post('/championsleague', [GoalscorerController::class, 'store'])->name("championsleague.store");
The next step would be to go to the GoalscorerController.php file and add some code to the store () function.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Goalscorer; class GoalscorerController extends Controller { public function create() { return view('create'); } 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 has been successfully added']); } }
Step 8: Display Error
If you press the Save Changes button and all fields are blank, the validator fails and displays errors.
Let’s try to fill form fields and save the data into the database.
If you press the Save changes button and all fields are filled, the data will be saved into the database.
Our goalscorers table looks like this:
That’s it.
shavindi pathirana
Thanks a lot. Im new to laravel. This helped me a lot. Keep uploading more.
tae
I got same problem so I changed scripts order jquery before bootstrap, it works
vipul dudhat
very nice and usefull
Indika Bandara
Thanks for the article. It really helped me. Thanks once again.
wazirkhan
how i show json responsive in view
Daniel
it’s good, but If I want to show the errors below each input. How could I do it? please help me.