Hello, laravel web developers! In this guide, we'll see how to add or remove multiple input fields in laravel 11 using jQuery. we'll create a dynamic add/remove more input field functionality with laravel 11.
Here, we'll create a form with input fields and add more buttons to add multiple input fields at a time. So, you can create dynamically add or remove multiple input fields with jQuery.
Laravel 11 Add or Remove Multiple Input Fields with jQuery
Step 1: Install Laravel 11 Application
Step 2: Create a Model and Migration
Step 3: Define Routes
Step 4: Create Controller
Step 5: Create Blade Files
Step 6: Run the Laravel 11 Application
In this step, we'll install the laravel 11 application using the following command.
composer create-project laravel/laravel laravel-11-example
Then, we'll create model and migration using the following command.
php artisan make:model Product -m
php artisan make:model ProductStock -m
Migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string("name");
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('products');
}
};
Product Stocks
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('product_stocks', function (Blueprint $table) {
$table->id();
$table->bigInteger("product_id");
$table->integer("quantity");
$table->integer("price");
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('product_stocks');
}
};
Then, we'll migrate the table into the database using the following command.
php artisan migrate
app/Models/Product.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Product extends Model
{
use HasFactory;
protected $fillable = ['name'];
/**
* Write code on Method
*
* @return response()
*/
public function stocks(): HasMany
{
return $this->hasMany(ProductStock::class);
}
}
app/Models/ProductStock.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ProductStock extends Model
{
use HasFactory;
protected $fillable = ['product_id', 'quantity', 'price'];
}
Now, we'll define the routes into the web.php file.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;
Route::get('/', function () {
return view('welcome');
});
Route::get('add-more', [ProductController::class, 'index']);
Route::post('add-more', [ProductController::class, 'store'])->name('add-more.store');
Next, we'll create a controller and store the data in the database.
app/Http/Controllers/ProductController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
class ProductController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$products = Product::paginate(10);
return view('add-more', compact('products'));
}
/**
* Write code on Method
*
* @return response()
*/
public function store(Request $request)
{
$rules = [ "name" => "required", "stocks.*" => "required" ];
foreach($request->stocks as $key => $value) {
$rules["stocks.{$key}.quantity"] = 'required';
$rules["stocks.{$key}.price"] = 'required';
}
$request->validate($rules);
$product = Product::create(["name" => $request->name]);
foreach($request->stocks as $key => $value) {
$product->stocks()->create($value);
}
return redirect()->back()->with(['success' => 'Product created successfully.']);
}
}
Then, we'll create a blade file and add the following HTML code to that file.
resources/views/add-more.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 11 Add or Remove Multiple Input Fields with jQuery - Techsolutionstuff</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="card mt-5">
<h3 class="card-header p-3">Laravel 11 Add/Remove More Fields - Techsolutionstuff</h3>
<div class="card-body">
@session('success')
<div class="alert alert-success" role="alert">
{{ $value }}
</div>
@endsession
<form method="post" action="{{ route('add-more.store') }}" enctype="multipart/form-data">
@csrf
<h5>Create Product:</h5>
<div class="form-group">
<label>Name:</label>
<input type="text" name="name" class="form-control" placeholder="Enter Name" value="{{ request()->old('name') }}" />
@error('name')
<p class="text-danger">{{ $message }}</p>
@enderror
</div>
<table class="table table-bordered mt-2 table-add-more">
<thead>
<tr>
<th colspan="2">Add Stocks</th>
<th><button class="btn btn-primary btn-sm btn-add-more"><i class="fa fa-plus"></i> Add More</button></th>
</tr>
</thead>
<tbody>
@php
$key = 0;
@endphp
@if(request()->old('stocks'))
@foreach(request()->old('stocks') as $key => $stock)
<tr>
<td>
<input type="number" name="stocks[{{$key}}][quantity]" class="form-control" placeholder="Quantity" value="{{ $stock['quantity'] ?? '' }}" />
@error("stocks.{$key}.quantity")
<p class="text-danger">{{ $message }}</p>
@enderror
</td>
<td>
<input type="number" name="stocks[{{$key}}][price]" class="form-control" placeholder="Price" value="{{ $stock['price'] ?? '' }}" />
@error("stocks.{$key}.price")
<p class="text-danger">{{ $message }}</p>
@enderror
</td>
<td><button class="btn btn-danger btn-sm btn-add-more-rm"><i class="fa fa-trash"></i></button></td>
</tr>
@endforeach
@else
<tr>
<td><input type="number" name="stocks[0][quantity]" class="form-control" placeholder="Quantity" /></td>
<td><input type="number" name="stocks[0][price]" class="form-control" placeholder="Price" /></td>
<td><button class="btn btn-danger btn-sm btn-add-more-rm"><i class="fa fa-trash"></i></button></td>
</tr>
@endif
</tbody>
</table>
<div class="form-group mt-2">
<button type="submit" class="btn btn-success btn-block"><i class="fa fa-save"></i> Submit</button>
</div>
</form>
<h5 class="mt-5">Product List:</h5>
<table class="table table-bordered data-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Total Quantity</th>
</tr>
</thead>
<tbody>
@forelse($products as $product)
<tr>
<td>{{ $product->id }}</td>
<td>{{ $product->name }}</td>
<td>{{ $product->stocks->sum('quantity') }}</td>
</tr>
@empty
<tr>
<td colspan="3">There are no products.</td>
</tr>
@endforelse
</tbody>
</table>
{!! $products->links('pagination::bootstrap-5') !!}
</div>
</div>
</div>
</body>
<script type="text/javascript">
$(document).ready(function(){
i = "{{$key}}";
$(".btn-add-more").click(function(e){
e.preventDefault();
i++;
$(".table-add-more tbody").append('<tr><td><input type="number" name="stocks['+i+'][quantity]" class="form-control" placeholder="Quantity" /></td><td><input type="number" name="stocks['+i+'][price]" class="form-control" placeholder="Price" /></td><td><button class="btn btn-danger btn-sm btn-add-more-rm"><i class="fa fa-trash"></i></button></td></tr>');
});
$(document).on('click', '.btn-add-more-rm', function(){
$(this).parents("tr").remove();
});
});
</script>
</html>
Now, run the laravel 11 application using the following code.
php artisan serve
You might also like: