Laravel – Dynamically Add or Remove Input Fields using jquery

Laravel – Dynamically Add or Remove Input Fields using jquery

Laravel – dynamically add multiple input fields and submit to database with jquery. In this tutorial, we will show you how to dynamically add/remove multiple input fields in form using jQuery, javascript in laravel.

As well as learn how to submit multiple input fields into database with server side validation in laravel app.

In this tutorial, we will guide you from scratch on how dynamically add/remove multiple input fields and submit to database with jquery and laravel.

In this tutorial post, we will make todo form with multiple input fields. Using this, You can dynamically add/remove multiple input todo form fields into your laravel form and submit to database with validation in laravel.

Add/remove multiple input fields dynamically with jquery laravel app will looks like, you can see in the following picture:

add/remove multiple input fields dynamically with jquery laravel

Laravel – Dynamically Add or Remove Input Fields using jquery

Let’s start our laravel add/remove multiple input fields dynamically using Jquery, javascript:

  • Step 1: Install Laravel App
  • Step 2: Add Database Details
  • Step 3: Create Migration & Model
  • Step 4: Add Routes
  • Step 5: Create Controller by Artisan
  • Step 6: Create Blade View
  • Step 7: Run Development Server

Step 1: Install Laravel App

First of all, open your terminal and run the following command to install or download laravel app for making dynamically add/remove multiple input fields and submit to database with jquery and laravel app:

cd xampp\htdocs

Then

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

Step 2: Add Database Details

In this step, Navigate to your downloaded root directory and open .env file. Then add your database details in .env file, as follow:

 DB_CONNECTION=mysql 
 DB_HOST=127.0.0.1 
 DB_PORT=3306 
 DB_DATABASE=here your database name here
 DB_USERNAME=here database username here
 DB_PASSWORD=here database password here

Step 3: Create Migration & Model

In this step, open a command prompt and run the following command:

php artisan make:model Todo -m

This command will create one model name Todo.php and as well as one migration file for the Todos table.

Then Navigate to database/migrations folder and open create_todos_table.php. Then update the following code into create_todos_table.php:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTodosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('todos', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('todos');
    }
}

Then navigate to app/Todo.php file. And the fielable property like following:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Todo extends Model
{
    protected $fillable = [
        'title', 'description'
    ];
}

After that, run the following command to migrate the table into your select database:

php artisan migrate

Step 4: Create Route

In this step, Navigate to the app/routes folder and open web.php file. Then update the following routes into your web.php file:

Route::get('add-remove-multiple-input-fields', 'DynamicAddRemoveFieldController@index');
Route::post('add-remove-multiple-input-fields', 'DynamicAddRemoveFieldController@store');

Step 5: Generate Controller by Artisan

In this step, open your terminal and run the following command to create ajax file upload controller file:

php artisan make:controller DynamicAddRemoveFieldController

This command will create a controller named DynamicAddRemoveFieldController.php file.

Next, Navigate to app/http/controllers/ folder and open DynamicAddRemoveFieldController.php. Then add the following file uploading methods into your DynamicAddRemoveFieldController.php file:

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Todo;

use Illuminate\Support\Facades\Validator;

class DynamicAddRemoveFieldController extends Controller
{
    public function index() 
    {
        return view("add-remove-input-fields");
    }
    public function store(Request $request)
    {
        $request->validate([
            'moreFields.*.title' => 'required',
            'moreFields.*.description' => 'required',
        ]);
    
        foreach ($request->moreFields as $key => $value) {
            Todo::create($value);
        }
    
        return back()->with('success', 'Todos Has Been Created Successfully.');
    }

}

Step 6: Create Blade View

In this step, create one blade view file named add-remove-multiple-input-fields.blade.php.

Now, navigate resources/views and create one file name add-remove-multiple-input-fields.blade.php Then update the following code into your add-remove-multiple-input-fields.blade.php file:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel - Add/remove multiple input fields dynamically using Jquery</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css">

    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/js/bootstrap.min.js"></script>
    
    <meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
   
<div class="container">
    
   
    <div class="card mt-3">
        <div class="card-header"><h2>Add/remove Multiple Input Todo Fields Dynamically using Jquery</h2></div>
       <div class="card-body">
            <form action="{{ url('add-remove-multiple-input-fields') }}" method="POST">
                @csrf
           
                @if ($errors->any())
                    <div class="alert alert-danger">
                        <ul>
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif
           
                @if (Session::has('success'))
                    <div class="alert alert-success text-center">
                        <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
                        <p>{{ Session::get('success') }}</p>
                    </div>
                @endif

                <table class="table table-bordered" id="dynamicAddRemove">  
                    <tr>
                        <th>Title</th>
                        <th>Description</th>
                        <th>Action</th>
                    </tr>
                    <tr>  
                        <td><input type="text" name="moreFields[0][title]" placeholder="Enter title" class="form-control" /></td>  
                        <td><input type="text" name="moreFields[0][description]" placeholder="Enter description" class="form-control" /></td>  
                        <td><button type="button" name="add" id="add-btn" class="btn btn-success">Add More</button></td>  
                    </tr>  
                </table> 
            
                <button type="submit" class="btn btn-success">Save</button>
            </form>
        </div>
    </div>

</div>
   
<script type="text/javascript">
   
    var i = 0;
       
    $("#add-btn").click(function(){
   
        ++i;
   
        $("#dynamicAddRemove").append('<tr><td><input type="text" name="moreFields['+i+'][title]" placeholder="Enter title" class="form-control" /></td><td><input type="text" name="moreFields['+i+'][description]" placeholder="Enter description" class="form-control" /></td><td><button type="button" class="btn btn-danger remove-tr">Remove</button></td></tr>');
    });
   
    $(document).on('click', '.remove-tr', function(){  
         $(this).parents('tr').remove();
    });  
   
</script>
  
</body>
</html>

Step 7: Run Development Server

Finally, run the following command to start the development server for your laravel – dynamically add/ remove multiple input fields using jquery app:

php artisan serve

Now, open your browser and hit the following URLs into it:

http://localhost:8000/add-remove-multiple-input-fields

If you want to remove public or public/index.php from URL In laravel, Click Me

Conclusion

dynamically add/remove multiple input fields and submit to database with jquery and laravel tutorial, you have learned how to dynamically add or remove multiple input fields using jquery , javascript in laravel app.

Recommended Laravel Posts

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *