Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

noblemfd's avatar

How to generate fixed dynamic input fields based on product_id count

I am using Laravel-5.8 to add dynamic input fields to an invoice. Already, I have written this code:

Product Model:

class Product extends Model
{
   protected $fillable = [
              'id',
              'name',
            ];
  public function invoice(){
    return $this->belongsToMany('App\Invoice');
 }
}

Invoice Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Invoice extends Model
{
    protected $fillable = [
              'id',
              'customer_id',
              'product_id',
              'invoice_date',
              'qty',
	  'price',
          ];
    public function customer(){
        return $this->belongsTo('App\Customer');
    }
    public function product(){
        return $this->belongsToMany('App\Product');
    }
}

Each invoice has one or more products.

Invoice Controller

Controller

public function create()
{
  $customers = Customer::all();
  $products = Product::all();
  return view('invoice.create', compact('customers','products'));
}

public function store(Request $request)
{
$request->validate([
    'customer_id' => 'required',
    'product_id' => 'required',
    'qty' => 'required',
    'price' => 'required',
    'dis' => 'required',
    'amount' => 'required',
]);
$invoice = new Invoice();
$invoice->customer_id = $request->customer_id;
$invoice->total = 1000;
$invoice->save();
foreach ( $request->product_id as $key => $product_id){
    $sale = new Product();
    $sale->qty = $request->qty[$key];
    $sale->price = $request->price[$key];
    $sale->dis = $request->dis[$key];
    $sale->amount = $request->amount[$key];
    $sale->product_id = $request->product_id[$key];
    $sale->invoice_id = $invoice->id;
    $sale->save();
 }
 return redirect('invoice/'.$invoice->id)->with('message','invoice created Successfully');
}

view

    <form  method="POST" action="{{route('invoice.store')}}">
@csrf
   <div class="form-group col-md-3">
     <label class="control-label">Customer Name</label>
     <select name="customer_id" class="form-control">
     <option>Select Customer</option>
     @foreach($customers as $customer)
          <option name="customer_id" value="{{$customer->id}}">{{$customer->name}} </option>
     @endforeach
     </select>                            
  </div>
  <div class="form-group col-md-3">
     <label class="control-label">Date</label>
     <input name="date"  class="form-control datepicker"  value="<?php echo date('Y-m-d')?>" type="date" placeholder="Enter your email">
  </div>

  <table class="table table-bordered">
    <thead>
       <tr>
           <th scope="col">Product Name</th>
           <th scope="col">Qty</th>
           <th scope="col">Price</th>
           <th scope="col">Discount</th>
           <th scope="col">Amount</th>
           <th scope="col"><a class="addRow"><i class="fa fa-plus"></i></a></th>
         </tr>
       </thead>
       <tbody>
           <tr>
             <td><select name="product_id[]" class="form-control productname" >
                <option>Select Product</option>
              @foreach($products as $product)
                   <option name="product_id[]" value="{{$product->id}}">{{$product->name}}</option>
              @endforeach
                     </select></td>
            <td><input type="text" name="qty[]" class="form-control qty" ></td>
            <td><input type="text" name="price[]" class="form-control price" ></td>
            <td><input type="text" name="dis[]" class="form-control dis" ></td>
           <td><input type="text" name="amount[]" class="form-control amount" ></td>
           <td><a   class="btn btn-danger remove"> <i class="fa fa-remove"></i></a></td>
         </tr>
       </tbody>
       <tfoot>
        <tr>
         <td></td>
         <td></td>
         <td></td>
         <td><b>Total</b></td>
         <td><b class="total"></b></td>
         <td></td>
        </tr>
       </tfoot>

    </table>
    <div >
       <button class="btn btn-primary" type="submit">Submit</button>
    </div>
</form>

javascipt

<script type="text/javascript">
    $(document).ready(function(){
        $('tbody').delegate('.productname', 'change', function () {
            var  tr = $(this).parent().parent();
            tr.find('.qty').focus();
        })
        $('tbody').delegate('.productname', 'change', function () {
            var tr =$(this).parent().parent();
            var id = tr.find('.productname').val();
            var dataId = {'id':id};
            $.ajax({
                type    : 'GET',
                url     :'{!! URL::route('findPrice') !!}',
                dataType: 'json',
                data: {"_token": $('meta[name="csrf-token"]').attr('content'), 'id':id},
                success:function (data) {
                    tr.find('.price').val(data.sales_price);
                }
            });
        });
        $('tbody').delegate('.qty,.price,.dis', 'keyup', function () {
            var tr = $(this).parent().parent();
            var qty = tr.find('.qty').val();
            var price = tr.find('.price').val();
            var dis = tr.find('.dis').val();
            var amount = (qty * price)-(qty * price * dis)/100;
            tr.find('.amount').val(amount);
            total();
        });
        function total(){
            var total = 0;
            $('.amount').each(function (i,e) {
                var amount =$(this).val()-0;
                total += amount;
            })
            $('.total').html(total);
        }
        $('.addRow').on('click', function () {
            addRow();
        });
        function addRow() {
            var addRow = '<tr>\n' +
                '         <td><select name="product_id[]" class="form-control productname " >\n' +
                '         <option value="0" selected="true" disabled="true">Select Product</option>\n' +
'                                        @foreach($products as $product)\n' +
'                                            <option value="{{$product->id}}">{{$product->name}}</option>\n' +
'                                        @endforeach\n' +
                '               </select></td>\n' +
'                                <td><input type="text" name="qty[]" class="form-control qty" ></td>\n' +
'                                <td><input type="text" name="price[]" class="form-control price" ></td>\n' +
'                                <td><input type="text" name="dis[]" class="form-control dis" ></td>\n' +
'                                <td><input type="text" name="amount[]" class="form-control amount" ></td>\n' +
'                                <td><a   class="btn btn-danger remove"> <i class="fa fa-remove"></i></a></td>\n' +
'                             </tr>';
            $('tbody').append(addRow);
        };
        $('.remove').live('click', function () {
            var l =$('tbody tr').length;
            if(l==1){
                alert('you cant delete last one')
            }else{
                $(this).parent().parent().remove();
            }
        });
    });
</script>

From the diagram below:

input fields

Product_id, qty, price are arrays. I want the number of rows of the generated dynamic fields to be based on the count of product_id in Product. For instance, if there are just five (5) products in the database, it should automatically generate five rows of Product_id, qty, price fields in the view blade.

What I mean is that as shown in the diagram, if have just 3 products, then the number of fields generated will be 3. If we have seven (7) products, 7 fields will be automatically generated without pressing the add button.

How do I modify my Controller and view blade code to achieve this?

Thanks

0 likes
1 reply
noblemfd's avatar

Hello everyone. In my controller I have:

$product_count = Product::where('is_published',0)->count();

What I mean is that how do I make addRow in the view blade to be equal to $product_count

Please or to participate in this conversation.