Danny971's avatar

Issue with Storing Received Quantities in Database

Hello everyone,

I'm facing an issue with my Laravel application where I need to store the received quantities of items in the database. Here's a brief overview of my setup:

I have two tables: requestorders and received. The requestorders table contains information about requested items, including the item name and the amount needed. The received table should store the received quantities for each item and the requestedItem name.

I've set up a form where the user can input the received quantities for each item. I'm using JSON and AJAX to submit the form data to the server. However, I'm having trouble getting the received quantities and item names from the form data and storing them in the database.

Here's a snippet of my code:

   //dd($request -> all());
      // Get the received quantities from the form data
    $receivedQuantities = $request->input('reev');

    
   
    foreach ($receivedQuantities as  $receivedQuantity) {
      $requestOrderId = $request->input('requestOrders')[$index]['requestOrderId'];
      $requestedItem = $request->input('requestOrders')[$index]['requestedItem'];
      $receivedQty = $receivedQuantity['receivedQuantity'];
 
      // Save the received quantity to the 'received' table
      $received = new received();
      $received->request_order_id = $requestOrderId;
      $received->reev = $receivedQty;
      $received->requestedItem = $requestedItem;
      $received->save();
  }

here is the js

function submitForm() {
  $(document).ready(function() {
    $('#submitButton').click(function(e) {
      e.preventDefault();
   
     // console.log('submitForm called');

      // Get the form values
      const decision = $('#decisionDropdown').val();
      const reason = $('#val-skill option:selected').text(); // Retrieve the selected option's reason text
      const caseId = $(this).data('case-id'); 

      // Prepare the data to be sent
      const formData = {
        decision: decision,
        reason: reason,
        caseID: caseId,
        
        receivedQuantities: $('input[name="reev[]"]').map(function() {
          const requestOrderId = $(this).data('request-order-id');
          const receivedQuantity = $(this).val();
          const requestedItem = $(this).closest('tr').find('td:eq(3)').text().trim();
          return {
            requestOrderId: requestOrderId,
            receivedQuantity: receivedQuantity,
            requestedItem: requestedItem
          };
        }).get()

      };


     


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

      // Perform the AJAX request
    $.ajax({
        url: '/fulfillment',
        type: 'POST',
        data: formData,
        dataType: 'json',
        headers: headers,

        success: function(response) {
          console.log('Form submission successful:', response);
          if (response.success) {
            showNotificationModal('success', 'Case approved');
      
            

           

            window.location.href = '/dashboard';
        
          } else {
            showNotificationModal('error', response.message);
          }
        },
        error: function(error) {
         // works anyways console.error('Form submission failed:', error);
        
          showNotificationModal('error', 'An error occurred');
        }
      }); 
    });
  });
}


here is the the html

   
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped table-responsive-sm">
                                        <thead>
                                            <tr>
                                                
                                                <th>CASE ID</th>
                                                <th>CATEGORY</th>
                                                <th>CATEGORY TOTAL</th>
                                                <th>REQUEST ORDER</th>
                                                <th>QUANTITY </th>
                                                <th>REEV </th>
                                                
                                            
                                            </tr>
                                        </thead>
                                        <tbody>
                                       
                                    

                             @foreach($requestorders  as $key => $ro)
                       <tr>
                           @if ($key == 0)
                        <td>{{$pendingcases->id}}</td>
                      <td> {{ explode(' ', $ro->requestedItem)[0] }}</td></td>
                     <td>{{ substr((string)$ro->amountNeeded, 0, 1) }}</td>
                    @else
                    <td></td>
                    <td></td>
                   <td></td>
                    @endif

    
        @if ($key >= 1)
        <td>{{$ro->requestedItem}}</td>
        <td>{{$ro -> amountNeeded}}</td>
        <td> <input type="number" name="reev[]" id = "reev" min ="0"  class="form-control"></td>

      
        
        @else
            <td></td>
            <td></td>
            <td></td>
          

        
           
        @endif
        
        
    </tr>
@endforeach


and when I put

 dd($request -> all());

i get

array:4 [ // app\Http\Controllers\CaseController.php:18
  "decision" => "APPROVE"
  "reason" => "Please select"
  "caseID" => "5"
  "receivedQuantities" => array:2 [
    0 => array:2 [
      "receivedQuantity" => "1"
      "requestedItem" => "Towel Set"
    ]
    1 => array:2 [
      "receivedQuantity" => "2"
      "requestedItem" => "Hangers"
    ]
  ]
]

which is true but it wont save to the db
0 likes
7 replies
hupp's avatar

@danny971 As per your dd output "reev" there is no key from the $request->input.

$receivedQuantities = $request->input('reev');

instead of above change to follow.

$receivedQuantities = $request->input('receivedQuantities');

Make sure there is $index defined in your code & try to replace these two lines

$requestedItem = $receivedQuantity['requestedItem'];
$receivedQty = (int)$receivedQuantity['receivedQuantity'];

if your are getting Item Name from $receivedQuantity than direct take from it. when you take Qty.

Let me know your feedback.

Danny971's avatar

@hupp i dont quite understand this section

$requestedItem = $receivedQuantity['requestedItem'];
$receivedQty = (int)$receivedQuantity['receivedQuantity'];
Danny971's avatar

@hupp

$receivedQuantities = $request->input('receivedQuantities'); dd("right here:", $receivedQuantities);

i see both requested quantities and requested items

Danny971's avatar

the foreach loop is giving me a single array of data when i have multiple in some cases

 $receivedQuantities = $request->input('receivedQuantities');
      
     dd( $receivedQuantities);

this seems to give me all the arrays of data needed

array:2 [ // app\Http\Controllers\CaseController.php:20
  0 => array:2 [
    "receivedQuantity" => "55"
    "requestedItem" => "Towel Set"
  ]
  1 => array:2 [
    "receivedQuantity" => "22"
    "requestedItem" => "Hangers"
  ]
]
hupp's avatar

@Danny971

$receivedQuantities = $request->input('receivedQuantities');
   
    foreach ($receivedQuantities as  $receivedQuantity) {
      $requestOrderId = $request->input('requestOrders')[$index]['requestOrderId'];
      $requestedItem = $receivedQuantity['requestedItem']; // this line changed
	  $receivedQty = (int)$receivedQuantity['receivedQuantity']; // this line changed
 
      // Save the received quantity to the 'received' table
      $received = new received();
      $received->request_order_id = $requestOrderId;
      $received->reev = $receivedQty;
      $received->requestedItem = $requestedItem;
      $received->save();
Danny971's avatar

@hupp

{message: "Undefined variable $index", exception: "ErrorException",…}
exception
: 
"ErrorException"
file
: 
"C:\xampp\htdocs\pos_cfr\app\Http\Controllers\CaseController.php"
line
: 
23
message
: 
"Undefined variable $index"

line 23 : $requestOrderId = $request->input('requestOrders')[$index]['requestOrderId'];
hupp's avatar

@danny971 $requestOrderId = $request->input('requestOrders')[$index]['requestOrderId']; in this line of question you have taken so i haven't change anything.

Please or to participate in this conversation.