Handlebar js is an amazing javascript library that compiles templates into JavaScript functions. This makes the template execution faster than most other template engines. In this tutorial, I will show you, how to use this handlebar js library in Laravel 9 application. We will create add more input field HTML forms using handlebars.js in Laravel.

We can create this repeater form in Laravel using jQuery javascript very easily, But in this tutorial, the purpose is to let you know how to use handlebar js in laravel and create a dynamic form repeater in Laravel. 

In this dynamically created form field based on selection, the user will select input and then add them.  Let's see how we can create dynamically created form fields based on selection.

laravel-9-handlebar-js-example

Step 1: Download Fresh Laravel

In this first step, we need a fresh Laravel 9 application for laravel dynamic form builder example. So download it by the below command:

composer create-project laravel/laravel example-app

 

Step 2:  Create Route

Now in this step, create a route like the one below to complete the form repeater laravel tutorial So define the resource route like the below:

routes/web.php

<?php

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

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('user', [TutorialController::class, 'index'])->name('user.index');
Route::post('user', [TutorialController::class, 'store'])->name('user.store');

 

Step 3: Create Controller

Now in this step, we have to create a TutorialController to define this method to create those two methods.

php artisan make:controller TutorialController

 

Now update the controller like the below:

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TutorialController extends Controller
{   
    public function index()
    {
        return view('welcome');
    }
    
    public function store(Request $request)
    {
        return $request;
    }
}

 

Step 4: Create Views

We are almost there. Just we have to create two views files before completing add multiple input fields dynamically with handebar js.

  • welcome.balde.php
  • app.blade.php

So create these files inside the following path and update them like below:

resources/views/layouts/app.blade.php

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>{{ config('app.name', 'Laravel') }}</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    @stack('style')
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}">
                    Laravelia
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                    <ul class="navbar-nav me-auto">

                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="navbar-nav ms-auto">
                        <!-- Authentication Links -->
                        @guest
                            @if (Route::has('login'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
                                </li>
                            @endif

                            @if (Route::has('register'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
                                </li>
                            @endif
                        @else
                            <li class="nav-item dropdown">
                                <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                    {{ Auth::user()->name }}
                                </a>

                                <div class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
                                    <a class="dropdown-item" href="{{ route('logout') }}"
                                       onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                        {{ __('Logout') }}
                                    </a>

                                    <form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
                                        @csrf
                                    </form>
                                </div>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>

        <main class="py-4" style="background-color: rgb(245, 245, 245);">
            @yield('content')
        </main>
    </div>
    @stack('script')
</body>
</html>

 

Now another one for date picker form.

resources/views/welcome.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Laravel 9 Handlebars JS Example | Laravelia</div>
                 <div class="card-body">
                    <div class="row">
                        <div class="col">
                            <label for="">Task</label>
                            <input type="text" class="form-control form-control-sm" id="task_name">
                        </div>
                        <div class="col">
                            <label for="">Priority</label>
                            <input type="text" class="form-control form-control-sm" id="priority">
                        </div>
                        <div class="col" style="margin-top:26px;">
                            <button id="addMore" class="btn btn-info btn-sm">Add More</button>
                        </div>
                    </div>
                    <form class="w-px-500 p-3 p-md-3" action="{{ route('user.store') }}" method="post">
                        @csrf
                            <table class="table table-sm table-bordered">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>Priority</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody id="addRow" class="addRow"></tbody>
                            </table>
                        <button type="submit" class="btn btn-success float-end">Submit</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('script')
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.6/handlebars.min.js"></script>
<script id="document-template" type="text/x-handlebars-template">
  <tr class="delete_item" id="delete_item">
      <td>
        <input type="text" name="task_name[]" value="@{{ task_name }}">
      </td>
      <td>
        <input type="text" name="priority[]" value="@{{ priority }}">
      </td>
      <td>
        <i class="removeaddmore" style="cursor:pointer;color:red;">Remove</i>
      </td>
  </tr>
 </script>
<script type="text/javascript">
$('body').on('click','#addMore',function(){
    var task_name = $("#task_name").val();
    var priority = $("#priority").val();
    var source = $("#document-template").html();
    var template = Handlebars.compile(source);
    var data = {
        task_name: task_name,
        priority: priority
    }
    var html = template(data);
    $("#addRow").append(html);
});
$('body').on('click','.removeaddmore',function(event){
    $(this).closest('.delete_item').remove();
});           
</script>
@endpush

 

Now if you submit the form, you will see the following output:

{
    "_token": "f2wPK7IhIcBgt0jWaf9HH0RLXcuNFD2w8polYKAZ",
    "task_name": [
        "Test1",
        "Test2",
        "Test3",
        "Test4"
    ],
    "priority": [
        "high",
        "high",
        "high",
        "high"
    ]
}

 

Read also: Create Add More Input Fields Form In Laravel

 

Conclusion

Now we know laravel dynamic form builder example. Hope this add multiple input fields dynamically with handebar js tutorial will help you. After completing this form repeater laravel tutorial, your concept will be clear about dynamically created form fields based on selection.