How to Dynamically load content in Bootstrap modal – Laravel 9

Bootstrap modal is a popup box that use to display information and input form.

You can also update its content dynamically each time when its open using AJAX.

In this tutorial, I show how you can load content on Bootstrap modal dynamically using jQuery AJAX in Laravel 9.

How to Dynamically load content in Bootstrap modal - Laravel 9


Contents

  1. Database Configuration
  2. Table structure
  3. Model
  4. Controller
  5. Route
  6. View
  7. Demo
  8. Conclusion

1. Database Configuration

Open .env file.

Specify the host, database name, username, and password.

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

2. Table structure

  • Create a new table employees using migration.
php artisan make:migration create_employees_table
  • Now, navigate to database/migrations/ folder from the project root.
  • Find a PHP file that ends with create_employees_table and open it.
  • Define the table structure in the up() method.
public function up()
{
    Schema::create('employees', function (Blueprint $table) {
       $table->bigIncrements('id');
       $table->string('username');
       $table->string('name');
       $table->string('email');
       $table->smallInteger('age');
       $table->timestamps();
    });
}
  • Run the migration –
php artisan migrate
  • The table is been created and I added some records to it.

3. Model

  • Create Employees Model.
php artisan make:model Employees
  • Open app/Models/Employees.php file.
  • Specify mass assignable Model attributes – username, name, email, and age using the $fillable property.

Completed Code

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Employees extends Model
{
   use HasFactory;

   protected $fillable = [
      'username','name','email','age'
   ];
}

4. Controller

  • Create EmployeesController controller.
php artisan make:controller EmployeesController
  • Import Employees model.

Create 2 methods –

  • index() – Fetch all records from employees table and assign to $data['employees']. Load index view and pass $data.
  • getEmployeeDetails() – This method takes employee id as a  parameter. Fetch a record by id from the employees table and create a layout. Assign $html to $response['html'].

Return $response in JSON format.

Completed Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Employees;

class EmployeesController extends Controller {

   public function index(){
      $data['employees'] = Employees::select('*')->get();
      return view('index',$data);
   }

   public function getEmployeeDetails($empid = 0){

      $employee = Employees::find($empid);

      $html = "";
      if(!empty($employee)){
         $html = "<tr>
              <td width='30%'><b>ID:</b></td>
              <td width='70%'> ".$employee->id."</td>
           </tr>
           <tr>
              <td width='30%'><b>Username:</b></td>
              <td width='70%'> ".$employee->username."</td>
           </tr>
           <tr>
              <td width='30%'><b>Name:</b></td>
              <td width='70%'> ".$employee->name."</td>
           </tr>
           <tr>
              <td width='30%'><b>Email:</b></td>
              <td width='70%'> ".$employee->email."</td>
           </tr>
           <tr>
              <td width='30%'><b>Age:</b></td>
              <td width='70%'> ".$employee->age."</td>
           </tr>";
      }
      $response['html'] = $html;

      return response()->json($response);
   }

}

5. Route

  • Open routes/web.php file.
  • Define 2 routes –
    • / – Load index view.
    • /getEmployeeDetails – This is GET type route for AJAX request.
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EmployeesController;

Route::get('/', [EmployeesController::class, 'index']); 
Route::get('/getEmployeeDetails/{empid}', [EmployeesController::class, 'getEmployeeDetails'])->name('getEmployeeDetails');

6. View

Create index.blade.php file in resources/views/.

HTML

Include Bootstrap and jQuery library.

<!-- CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" >

<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" ></script>

Create #empModal Modal where show employee information using jQuery AJAX.

Loop on $employees to list records in <table >. Added a <button > in the last column to open the modal on click. Defined employee id in data-id attribute.

Script

  • Defined click event on <button class='viewdetails' >.
  • Read employee id from data-id attribute and assign to id variable.
  • Empty the modal <table ><tbody>.
  • Send AJAX GET request to getEmployeeDetails route where pass employee id as parameter.
  • On successful callback replace modal <table id="tblempinfo"><tbody> data with response and open #empModal modal.

Completed Code

<!DOCTYPE html>
<html>
<head>
   <title>How to Dynamically load content in Bootstrap modal - Laravel 9</title>

   <!-- Meta -->
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <meta charset="utf-8">

   <!-- CSS -->
   <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" >

   <!-- Script -->
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
   <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" ></script>

</head>
<body>
   <div class='container'>

      <!-- Modal -->
      <div class="modal fade" id="empModal" >
         <div class="modal-dialog">

            <!-- Modal content-->
            <div class="modal-content">
               <div class="modal-header">
                  <h4 class="modal-title">Employee Info</h4>
                  <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
               </div>
               <div class="modal-body">
                   <table class="w-100" id="tblempinfo">
                      <tbody></tbody>
                   </table>
               </div>
               <div class="modal-footer">
                   <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button>
               </div>
            </div>
         </div>
      </div>

      <!-- Employees List -->
      <table class="table mt-5" border='1' id='empTable' style='border-collapse: collapse;'>
         <thead>
            <tr>
               <th>S.no</th>
               <th>Username</th>
               <th>Name</th>
               <th>Email</th>
               <th>&nbsp;</th>
            </tr>
         </thead>
         <tbody>
         @php
         $sno = 0;
         @endphp
         @foreach($employees as $employee)
            <tr>
              <td>{{ ++$sno }}</td>
              <td>{{ $employee->username }}</td>
              <td>{{ $employee->name }}</td>
              <td>{{ $employee->email }}</td>
              <td><button class='btn btn-info viewdetails' data-id='{{ $employee->id }}' >View Details</button></td>
            </tr>
         @endforeach
         </tbody>
      </table>

   </div>

   <!-- Script -->
   <script type='text/javascript'>
   $(document).ready(function(){

      $('#empTable').on('click','.viewdetails',function(){
          var empid = $(this).attr('data-id');

          if(empid > 0){

             // AJAX request
             var url = "{{ route('getEmployeeDetails',[':empid']) }}";
             url = url.replace(':empid',empid);

             // Empty modal data
             $('#tblempinfo tbody').empty();

             $.ajax({
                 url: url,
                 dataType: 'json',
                 success: function(response){

                     // Add employee details
                     $('#tblempinfo tbody').html(response.html);

                     // Display Modal
                     $('#empModal').modal('show'); 
                 }
             });
          }
      });

   });
   </script>
</body>
</html>

7. Demo

View Demo


8. Conclusion

Send the AJAX request to load data when button gets clicked to display modal. Update modal data before calling modal('show').

If you found this tutorial helpful then don't forget to share.

Leave a Comment