1

Hey guys I'm a bit confused with this. How do I input multi row forms in Laravel 5.5 using ajax? The idea is to add items and when adding items the Item number increments, then I want to save this table in my database: enter image description here

Here is my code for the blade with its script:

pr-items.blade.php

@extends('layouts.app')
@section('content')

<div class="container-fluid">
<!-- Your main wrapper -->

    <div class="row">
        <div class="col-md-12">
            <div class="panel panel-default">
                <div class="panel-heading"><h3 class="panel-title">Add Items</h3></div>
                <div class="panel-body">

                    <form name="add_item" id="add_item" class="form-inline">
                    {{ csrf_field() }}


                      <div class="form-group">
                        <label for="pr_form_number">PR Form Number: </label>
                        <input type="text" class="form-control" name="pr_number" value="{{$pr_details}}" readonly required><br><br>
                      </div>

                      <div class="table-responsive">
                        <table class='table table-bordered table-hover' id="tab_logic">
                            <thead>
                                <tr class='info'>
                                    <th style='width:10%;'>ITEM NO.</th>
                                    <th style='width:10%;'>QTY</th>
                                    <th style='width:10%;'>UNIT</th>
                                    <th style='width:30%;'>DESCRIPTION</th>
                                    <th style='width:10%;'>COST PER UNIT</th>
                                    <th style='width:10%;'>COST PER ITEM</th>
                                    <th style='width:10%;'>ACTION</th>
                                </tr>
                            </thead>
                            <thead>
                                <tr id="addr0">
                                    <td class="custom-tbl"><input class='form-control input-sm'style='width:100%;' type="text" value="1" id="pr_item0" name="pr_item[]" readonly required></td>
                                    <td class="custom-tbl"><input class='form-control input-sm' style='width:100%;' type="text" id="pr_qty0" oninput='multiply(0);' name="pr_qty[]"></td>
                                    <td class="custom-tbl"><input class='form-control input-sm' style='width:100%;' type="text" id="pr_unit0" name="pr_unit[]"></td>
                                    <td class="custom-tbl"><input class='form-control input-sm' style='width:100%;' type="text" id="pr_desc0" name="pr_desc[]"></td>
                                    <td><input class='form-control input-sm' style='width:100%;' type="text" id="pr_cpu0" oninput='multiply(0);' name="pr_cpu[]"></td>
                                    <td class="custom-tbl"><input class='estimated_cost form-control input-sm' id="pr_cpi0" style='width:100%;' type="text" name="pr_cpi[]" readonly></td>
                                    <td class="custom-tbl"><button type="button" id="add" class="btn btn-info btn-sm"><span class="glyphicon glyphicon-plus"></span></button></td>
                                </tr>
                            </thead>
                            <tbody id="dynamic_field">

                            <tbody>
                            <tfoot>
                                <tr class='info'>
                                    <td style='width:65%;text-align:right;padding:4px;' colspan='5'>GRAND TOTAL:</td>
                                    <td style='padding:0px;'>

                                            <input style='width:100%;' type='text' class='form-control input-sm' id='grand_total' name='grand_total' value='0' readonly required>

                                    </td>

                            </tfoot>

                        </table>
                      </div>


                      <button type="button" id="submit" name="submit" class="btn btn-default">Submit</button>
                    </form>

                </div>

            </div>
        </div>

    </div>


</div>



@endsection

@section('script')
<script type="text/javascript">



$(document).ready(function(){      
      var postURL = "<?php echo url('addmore'); ?>";
      var i=1;  


      $('#add').click(function(){
           i++;  
           $('#dynamic_field').append('<tr id="row'+i+'" class="dynamic-added"><td class="custom-tbl"><input id="pr_item'+i+'" class="form-control input-sm"style="width:100%;" type="text" value="'+i+'" name="pr_item[]" readonly required></td><td class="custom-tbl"><input id="pr_qty'+i+'"class="form-control input-sm" style="width:100%;" type="text" oninput="multiply('+i+');" name="pr_qty[]"></td><td class="custom-tbl"><input id="pr_unit'+i+'"class="form-control input-sm" style="width:100%;" type="text" name="pr_unit[]"></td><td class="custom-tbl"><input id="pr_desc'+i+'" class="form-control input-sm" style="width:100%;" type="text" name="pr_desc[]"></td><td class="custom-tbl"><input id="pr_cpu'+i+'" class="form-control input-sm" style="width:100%;" type="text" oninput="multiply('+i+');" name="pr_cpu[]"></td><td class="custom-tbl"><input id="pr_cpi'+i+'" class="estimated_cost form-control input-sm" style="width:100%;" type="text" name="pr_cpi[]" readonly></td><td class="custom-tbl"><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn-sm btn_remove"><span class="glyphicon glyphicon-remove"></span></button></td></tr>');  
      });  


      $(document).on('click', '.btn_remove', function(){  
           var button_id = $(this).attr("id");   
           $('#row'+button_id+'').remove();  
      });

      $.ajaxSetup({
          headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
      });


      $('#submit').click(function(){            
           $.ajax({  
                url:"{{route('pr.items.add')}}",  
                method:"POST",  
                data:$('#add_item').serialize(),
                type:'json',

           });  
      });  

    });




</script>

<script type="text/javascript">
    function multiply(id)
        {
            var total1=parseFloat($('#pr_qty'+id).val())*parseFloat($('#pr_cpu'+id).val());
            $("input[id=pr_cpi" + id + "]").val(total1);
            grandTotal();
        }
function grandTotal()
        {
            var items = document.getElementsByClassName("estimated_cost");
            var itemCount = items.length;
            var total = 0;
            for(var i = 0; i < itemCount; i++)
            {
                total = total +  parseFloat(items[i].value);
            }
            document.getElementById('grand_total').value = total;
        }
</script>

@endsection

And here is a part of my controller for storing its data

PurchaseRequestItemController.php

 public function store(Request $request)
    {
        //


        $rules = [];


        foreach($request->input('pr_item') as $key => $value) {
            $rules["pr_item.{$key}"] = 'required';
            $rules["pr_qty.{$key}"] = 'required';
            $rules["pr_unit.{$key}"] = 'required';
            $rules["pr_desc.{$key}"] = 'required';
            $rules["pr_cpu.{$key}"] = 'required';
            $rules["pr_cpi.{$key}"] = 'required';
        }


        $validator = Validator::make($request->all(), $rules);


        if ($validator->passes()) {


            foreach($request->input('pr_item') as $key => $value) {

                $Record=new PurchaseRequestItemModel;

                $Record->pr_form_number = $request->get('pr_number');
                $Record->item_no = $request->get('pr_item');
                $Record->pr_qty = $request->get('pr_qty');
                $Record->pr_unit = $request->get('pr_unit');
                $Record->pr_description =$request->get('pr_desc') ; 
                $Record->pr_cost_per_unit =$request->get('pr_cpu') ;
                $Record->pr_estimated_cost =$request->get('pr_cpi') ;

                $Record->save();
            }


            return response()->json(['success'=>'done']);
        }else{

        return response()->json(['error'=>$validator->errors()->all()]);}




    }

edit: Also my form is an array. How do I also make sure that after saving I can view the table as it is?

It also returns this error when I save enter image description here

11
  • what was the issue in current code? Commented Oct 23, 2018 at 5:42
  • @BhargavChudasama It does not save. It returns an error. Also I am looking for a more efficient way of doing hte process of saving multiple forms Commented Oct 23, 2018 at 5:44
  • so what was the error? Commented Oct 23, 2018 at 5:45
  • @BhargavChudasama it's up there, edited my question. :) Commented Oct 23, 2018 at 5:46
  • error 500 is server error. Commented Oct 23, 2018 at 5:50

4 Answers 4

2

For example $request->get('pr_number'); this is an array so can't get the specific value without defining the index. You have to define the index of array. Try this. Hope it will work.

foreach($request->input('pr_item') as $key => $value) {

            $Record=new PurchaseRequestItemModel;

            $Record->pr_form_number = $request->get('pr_number')[$key];
            $Record->item_no = $request->get('pr_item')[$key];
            $Record->pr_qty = $request->get('pr_qty')[$key];
            $Record->pr_unit = $request->get('pr_unit')[$key];
            $Record->pr_description =$request->get('pr_desc')[$key]; 
            $Record->pr_cost_per_unit =$request->get('pr_cpu')[$key];
            $Record->pr_estimated_cost =$request->get('pr_cpi')[$key];

            $Record->save();
        }
Sign up to request clarification or add additional context in comments.

Comments

2

use this

$pr_item=$request->get('pr_item');
$pr_qty=$request->get('pr_qty');
$pr_unit=$request->get('pr_unit');
$pr_desc=$request->get('pr_desc');
$pr_cpu=$request->get('pr_cpu');
$pr_cpi=$request->get('pr_cpi');
for($i = 0; $i < count($request->get('pr_item')); $i++)
            $Record=new PurchaseRequestItemModel;
            $Record->pr_form_number =    $request->get('pr_number');
            $Record->item_no =           $pr_item[$i];
            $Record->pr_qty =            $pr_qty[$i];
            $Record->pr_unit =           $pr_unit[$i];
            $Record->pr_description =    $pr_desc[$i]; 
            $Record->pr_cost_per_unit =  $pr_cpu[$i];
            $Record->pr_estimated_cost = $pr_cpi[$i];
            $Record->save();
        }

Comments

1
 Use $request->all() and fetch values as below it will work.

 foreach( $request->all() as $value ) {
    $record = new PurchaseRequestItemModel;
    $record->pr_form_number = $value['pr_number'];
    $record->item_no = $value['pr_item'];
    $record->pr_qty = $value['pr_qty'];
    $record->pr_unit = $value['pr_unit'];
    $record->pr_description =$value['pr_desc')];
    $record->pr_cost_per_unit =$value['pr_cpu')];
    $record->pr_estimated_cost =$value['pr_cpi')];
    $record->save();
}

Comments

0

Hope this will help you

foreach($request->input('pr_item') as $key => $value) 
{
     $item = new PurchaseRequestItemModel;
     $item ->pr_form_number = $request->get('pr_number')[$key];
     $item ->item_no = $request->get('pr_item')[$key];
     // mention other fields here
     $item ->save();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.