Add or remove dynamically input fields using jQuery | Laravel Array validation

In this article, we will share with you how to add or remove dynamically input fields using jQuery with laravel validation. many times we need this type of functionality in our web application. like some module has the same information with different values, in this case, we should do this using add or remove input fields dynamically using jQuery in our HTML form.

Here, we not only show how to create add or remove dynamically input fields in HTML form but how to apply laravel array validation on it. before you are never have done this type of functionality then don't worry here I will share with you all step by step.

In this article, we will be done to add or remove input fields dynamically in HTML form on IP / Website approval functionality. in many API integrations, we first need to add our site's IP and website name there and then we will able to call API's all methods like POST, GET, OPTION, etc..

Preview

Step - 1 Create Laravel Application

First, we need to create one new fresh laravel application help of the following composer command.

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

Step - 2 Configure Database Setting.

Now, into the second step, we should configure database settings in .env the file just open your .env file and make the following changes. set your database name, username, and password.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=database_username
DB_PASSWORD=database_password

Step - 3 Create Migration

Now, we need to create a migration for ip_approve_tbl the table. run the following command in your terminal.

php artisan make:migration create_ip_approve_tbl

After running this command, then open that created file that will be created on database/migrations the folder. just open it and put the following code into that migration file.

<?php

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

class CreateIpApproveTbl extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('ip_approve_tbl', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('user_id')->default(0);
            $table->string('website_name');
            $table->string('ip');
            $table->enum('is_approved', ['0','1'])->default('0');
            $table->timestamps();
        });
    }

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

and then run php artisan migrate commands in your terminal. then your ip_approve_tbl table will be created into your database, which you set into in your project .env file.

Step - 4 Create Route Resource.

Now, we need to create the following laravel resource route in your routes/web.php. if you don't know about laravel route resource then click this link Laravel route resource and get more information about it.

Route::resource('ipapprove', 'IpApproveController');

Step - 5 Create Controller.

Now, we need to create IpApproveController.php a file in app\Http\Controllers folder. just run the following command in your terminal and create your controller.

php artisan make:controller IpApproveController --resource

Just, open your IpApproveController.php file and write the following code into this controller.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\IpApprove;
use Session;

class IpApproveController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->IpApprove = new IpApprove;

        $this->title = 'IP Approve';
        $this->path = 'ipapprove';
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = $this->IpApprove->getData();
        
        return view($this->path.'.index', compact('data'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view($this->path.'.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $input = $request->all();
        // dd($request->all());
        foreach ($request->get('ipapprove') as $key => $value) {
            $validation['ipapprove.'.$key.'.website_name'] = 'required';
            $validation['ipapprove.'.$key.'.ip'] = 'required';
        }
        $this->validate($request, $validation);

        \DB::beginTransaction();
        try {
            // Store into database
            foreach ($request->get('ipapprove') as $key => $value) {
                $data['website_name'] = $value['website_name']; 
                $data['ip'] = $value['ip'];
                $data['user_id'] = 1; //Here you should pass auth user id.
                IpApprove::create($data);
            }

        } catch(Exception $e) {
            \DB::rollBack();
            Session::put('error','Something Went Wrong. Please try again..!!');
            return redirect()->back();
        }

        \DB::commit();

        Session::put('success','Data store Successfully!!');
        return redirect()->route('ipapprove.index');
    }
}

Step - 6 Create Model.

Now create app\IpApprove.php model and write into this model the following code.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class IpApprove extends Model
{
    protected $table = 'ip_approve_tbl';
    protected $guarded = array();

    public function getData()
    {
        return static::orderBy('created_at','desc')->paginate(5);
    }

    public function storeData($input)
    {
        return static::create($input);
    }
}

Step - 7 Create Index Blade Files

After done controller and model then we need to create index.blade.php a file in resources/views/ipapprove folder. in index blade, we simply list all the inserted ip's data.

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12 text-right">
            <a href="{{ route('ipapprove.create') }}" class="btn btn-info pull-right">Add IPs</a>
        </div>
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">{{ __('IPs Listing') }}</div>

                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered datatable">
                            <thead>
                                <tr>
                                    <th>Id</th>
                                    <th>Website</th>
                                    <th>IP</th>
                                    <th>Status</th>
                                    <th width="150" class="text-center">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @if(!empty($data) && $data->count())
                                    @foreach($data as $key=>$value)
                                        <tr>
                                            <td>{{ $value->id }}</td>
                                            <td>{{ $value->website_name }}</td>
                                            <td>{{ $value->ip }}</td>
                                            <td>
                                                @if($value->is_approved == '1')
                                                    <label class="label label-success">Approved</label>
                                                @else
                                                    <label class="label label-danger">Pending</label>
                                                @endif
                                            </td>
                                            <td class="text-center">
                                                <a href="{{ route('ipapprove.edit', $value->id) }}" class="btn btn-success">Edit</a>
                                            </td>
                                        </tr>
                                    @endforeach
                                @else
                                    <tr>
                                       <td colspan="5" class="text-center">No any records right now found..</td> 
                                    </tr>
                                @endif
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Step - 8 Crete Store Blade File.

After done controller and model then we need to create create.blade.php a file in resources/views/ipapprove folder. we can put here simple create an HTML page layout and write here code how to add or remove dynamic input fields in our store form. we can make it the help of some jQuery/HTML code.

Before, create create.blade.php file you should add two extra sections in your layout.blade.php file for add CSS and Script code.

@extends('layouts.app')

@section('style')
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
@endsection

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            @if($message = Session::get('error'))
            <div class="alert alert-danger alert-dismissible" role="alert">
                <button type="button" class="close" data-dismiss="alert">×</button>
                <div class="alert-icon contrast-alert">
                    <i class="fa fa-times"></i>
                </div>
                <div class="alert-message">
                    <span><strong>Error!</strong> {{ $message }}</span>
                </div>
            </div>
            @endif
            {!! Session::forget('error') !!}
            @if($message = Session::get('success'))
            <div class="alert alert-success alert-dismissible" role="alert">
                <button type="button" class="close" data-dismiss="alert">×</button>
                <div class="alert-icon contrast-alert">
                    <i class="fa fa-times"></i>
                </div>
                <div class="alert-message">
                    <span><strong>Success!</strong> {{ $message }}</span>
                </div>
            </div>
            @endif
            {!! Session::forget('success') !!}
        </div>        
    </div>
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Add IPs') }}</div>

                <div class="card-body">
                    <form method="POST" action="{{ route('ipapprove.store') }}">
                        @csrf
                        <table class="table">
                        <thead>
                            <tr>
                                <th>No.</th>
                                <th>Website Name</th>
                                <th>IP's</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody id="ipapprove">
                            @if(old('ipapprove')!="")
                                <div id="countVar" data-count = "{{ count(old('ipapprove')) }}"></div>
                                @foreach(old('ipapprove') as $key => $value)
                                    <tr data-id={{ ($key == 0)?$key+1:$key }}>
                                        <th scope="row">{{ ($key == 0)?$key+1:$key }}</th>
                                        <td>
                                            <input type="text" class="form-control @error('ipapprove.'.$key.'.website_name') is-invalid @enderror" name="ipapprove[{{$key}}][website_name]" value="{{ old('ipapprove.'.$key.'.website_name') }}" placeholder="Website Name" autofocus>
                                            @error('ipapprove.'.$key.'.website_name')
                                                <span class="invalid-feedback" role="alert">
                                                    <strong>{{ $message }}</strong>
                                                </span>
                                            @enderror
                                        </td>
                                        <td>
                                            <input type="text" class="form-control @error('ipapprove.'.$key.'.ip') is-invalid @enderror" name="ipapprove[{{$key}}][ip]" value="{{ old('ipapprove.$key.ip') }}" placeholder="IP" autofocus>
                                            @error('ipapprove.'.$key.'.ip')
                                                <span class="invalid-feedback" role="alert">
                                                    <strong>{{ $message }}</strong>
                                                </span>
                                            @enderror
                                        </td>                                 
                                        <td class="text-center">
                                            @if($key == 0)
                                                <button type="button" class="btn btn-success plus"> <i class="fa fa-plus"></i> </button>
                                            @else
                                                <button type="button" class="btn btn-success plus"> <i class="fa fa-plus"></i> </button>
                                                <button type="button" class="btn btn-danger minus"> <i class="fa fa-minus"></i> </button>
                                            @endif
                                        </td>
                                    </tr>
                                @endforeach
                            @else
                            <div id="countVar" data-count = "0"></div>
                            <tr data-id="1">
                                <th scope="row">1</th>
                                <td>
                                    <input type="text" class="form-control" name="ipapprove[1][website_name]" placeholder="Website Name" autofocus>
                                    @error('ipapprove.1.website_name')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </td>
                                <td>
                                    <input type="text" class="form-control" name="ipapprove[1][ip]" placeholder="IP" autofocus>
                                    @error('ipapprove.1.ip')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </td>                                 
                                <td class="text-center">
                                    <button type="button" class="btn btn-success plus"> <i class="fa fa-plus"></i> </button>
                                </td>
                            </tr>
                            @endif
                        </tbody>
                      </table>                     

                        <div class="form-group row mb-0">
                            <div class="col-md-12">
                                <button type="submit" class="btn btn-primary btn-block">
                                    {{ __('SUBMIT') }}
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('script')
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
    $('body').on('click', '.plus', function() { 
        // i = $('#tab_logic tr').length; 
        var i =  $('#ipapprove tr:last').data('id');
        i = i+1;
        $('#ipapprove').append('<tr data-id="'+ i +'">\
            <th scope="row">'+ i +'</th>\
            <td>\
                <input placeholder="Website Name" class="form-control" name="ipapprove['+ i +'][website_name]" type="text">\
            </td>\
            <td>\
                <input placeholder="IP" class="form-control" name="ipapprove['+ i +'][ip]" type="text">\
            </td>\
            <td class="text-center">\
                <button type="button" class="btn btn-success plus"> <i class="fa fa-plus"></i> </button>\
                <button type="button" class="btn btn-danger minus"> <i class="fa fa-minus"></i> </button>\
            </td>\
        </tr>');
        // i++;
    });
    $('body').on('click', '.minus', function() {
        $(this).closest('tr').remove();
        // i--;
    });
</script>
@endsection

After, do this all step your dynamic add or remove input fields in the form is ready to run and test it is working fine or not? just run the below command in your project root directory for run the laravel application in a web browser.

php artisan serve

Then open your web browser and hit the following URL in the browser.

https://localhost:8000/ipapprove

Conclusion

As you can see, dynamic add or remove input fields with laravel is very easy to built the help of some jQuery code logic.

We hope these tutorials help everyone. if you have any issues or questions regarding this article. so, please comment below. Thanks.