How to create a common dynamic modal in Laravel?

This guide provides step-by-step process of creating a reusable modal component that can be used across your Laravel application, Whether you are a beginner or an experienced Laravel developer, this guide will help you streamline your web development process and enhance the user experience of your web applications.

So lets get started, First we will create a controller named ModalController, So to create a controller run the command below.

php artisan make:controller ModalController

Now we will create a get route to display modal button and other will be to show dynamic content in modal, So we will add routes in web.php and create a function in ModalController.php

Route::get('dynamic-modal', [\App\Http\Controllers\ModalController::class, 'dynamicModal'])->name('dynamic-modal');
Route::get('modal-content', [\App\Http\Controllers\ModalController::class, 'modalContent'])->name('modal-content');
class ModalController extends Controller
{
    public function dynamicModal()
    {
        return view('dynamic-modal.index');
    }
}

resources/views/dynamic-modal/index.blade.php


Note : I have used a custom toast notification function for error handling, If you wish to learn how to create a toast notification then please check this post 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Dynamic Modal</title>

    <!-- BOOTSTRAP -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
    <!-- Styles -->
    <style>
        body {
            background: #f7f7f7;
        }

        .form-box {
            max-width: 80%;
            margin: auto;
            padding: 50px;
            background: #ffffff;
            border: 10px solid #f2f2f2;
            margin-top: 100px;
        }

        h1, p {
            text-align: center;
            padding-bottom: 40px;
        }

        input, textarea {
            width: 100%;
        }
    </style>
</head>
<body>

<div class="form-box text-center">
    <h1>Dynamic Modal</h1>
    <button class="btn btn-primary" onclick="dynamicModal('{{route('modal-content')}}')">{{ __('Create User') }}</button>
</div>

<!-- BOOTSTRAP MODAL STARTS -->
<div class="modal fade" id="dynamic-model" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
        </div>
    </div>
</div>
<!-- BOOTSTRAP MODAL END -->

<!-- JQUERY, BOOTSTRAP -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<!-- SCRIPT STARTS -->
<script>
    function dynamicModal( url, size = 'md'){
        var modal_id = '#dynamic-model';
        $(modal_id+" .modal-dialog").addClass('modal-' + size);
        $.ajax({
            url: url,
            success: function (data) {
                if (data.error == undefined) {
                    $(modal_id + ' .modal-content').html(data);
                    $(modal_id).modal('show');
                } else {
                  createToast('error', data.error);
                }
            },
            error: function (data) {
               createToast('error', 'Something went wrong');
            }
        });
    }
</script>
<!-- SCRIPT END -->
</body>
</html>

In ModalController we will create a function named modalContent() this function will return a view, We will create a user form for view file. 

public function modalContent()
{
    return view('dynamic-modal.user-form');
}

resources/views/dynamic-modal/user-form.blade.php

<form method="POST" action="#" enctype="multipart/form-data">
    @csrf
    <div class="modal-header">
        <h5 class="modal-title">{{ __('Create Blog Category') }}</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-6">
                <label for="name" class="form-control-label">Name</label>
                <input type="text" name="name" class="form-control" id="name" value="{{ old('name') }}">
            </div>
            <div class="form-group col-md-6">
                <label for="email" class="form-control-label">Email</label>
                <input type="email" name="email" class="form-control" id="email" value="{{ old('email') }}">
            </div>
            <div class="form-group col-md-6">
                <label for="password" class="form-control-label">Password</label>
                <input type="password" name="password" class="form-control" id="password">
            </div>
            <div class="form-group col-md-6">
                <label for="password_conformation" class="form-control-label">Confirm Password</label>
                <input type="password" name="password_conformation" class="form-control" id="password_conformation">
            </div>
        </div>
        <div class="modal-footer bg-whitesmoke">
            <button type="submit" class="btn btn-primary">{{ __('Save') }}</button>
        </div>
    </div>
</form>

If you want to validate form then you can create another function and class to required fields.

<form method="POST" action="#" enctype="multipart/form-data" class="needs-validation">
<div class="form-group col-md-6">
    <label for="name" class="form-control-label">Name</label>
    <input type="text" name="name" class="form-control required" id="name" value="{{ old('name') }}">
    <div class="invalid-feedback">
        {{ __('Name field is required') }}
    </div>
</div>
$(document).on('click', 'form.needs-validation button[type=submit]', function(e) {
    e.preventDefault();
    var i = 0;
    $(this).parents('form').find('input.required,select.required,textarea.required').each(function( value ) {
        if($(this).val() == '')
        {
            $(this).focus();
            $(this).addClass('is-invalid');
            i = i + 1;
            return false;
        }
    });
    if(i == 0){
        $(this).parents('form').submit();
    }
});