1

I'm working on a Laravel application where users can search for products or categories and specify quantities. However, the quantities entered for products are not being remembered when users search for different products or categories within the same view. The issue persists despite using Laravel sessions to store the quantities.

Problem:

  1. When a user searches for products and enters quantities, the quantities are only remembered for the last category or product searched.

  2. The session appears to only retain data for the most recent search.

TESTED IMPLEMENTATION:

  1. first test
// Store selected quantities in the session
$existingQuantities = $req->session()->get('quantities', []);
$newQuantities = $req->input('quantity', []);

// Filter out null values
$newQuantities = array_filter($newQuantities, function($value) {
    return $value !== null;
});

// Merge existing and new quantities
$mergedQuantities = array_merge($existingQuantities, $newQuantities);

// Update session with merged quantities
$req->session()->put('quantities', $mergedQuantities);

// Debugging
dd($req->session()->get('quantities'));

// Retrieve categories and products
$categories = Category::with(['products.inventories'])->get();
$orderItems = [];
$categoryTotals = [];

foreach ($categories as $category) {
    foreach ($category->products as $product) {
        if (isset($mergedQuantities[$product->id]) && $mergedQuantities[$product->id] > 0) {
            $quantity = $mergedQuantities[$product->id];
            $orderItems[] = [
                'category' => $category->category_name,
                'product_name' => $product->product_name,
                'quantity' => $quantity
            ];

            if (!isset($categoryTotals[$category->category_name])) {
                $categoryTotals[$category->category_name] = 0;
            }
            $categoryTotals[$category->category_name] += $quantity;
        }
    }
}

// Insert order items into the database
foreach ($orderItems as $orderItem) {
    DB::table('requestorder')->insert([
        'family_id' => $familyId,
        'category' => $orderItem['category'],
        'categoryTotal' => $categoryTotals[$orderItem['category']],
        'requestedItem' => $orderItem['product_name'],
        'amountNeeded' => $orderItem['quantity'],
        'daterequested' => now()
    ]);
}

// Clear session after order is submitted
$req->session()->forget('quantities');
  1. second implementation test
 // Retrieve existing quantities from the session
    $existingQuantities = $req->session()->get('quantities', []);

    // Retrieve new quantities from the request
    $newQuantities = $req->input('quantity', []);

    // Log or var_dump existing and new quantities for debugging
    var_dump('Existing Quantities:', $existingQuantities);
    var_dump('New Quantities:', $newQuantities);

    // Iterate over the new quantities
    foreach ($newQuantities as $productId => $quantity) {
        // Log or var_dump each quantity to see why some might be null
        var_dump("Processing Product ID: $productId, Quantity: $quantity");

        // Store all quantities, including null, in the session
        $quantityData = [
            'productid' => $productId,
            'quantity' => $quantity
        ];

        // Use Session::push() to add each quantity to the session
        $req->session()->push('quantities', $quantityData);
    }

    // Retrieve the updated quantities from the session
    $updatedQuantities = $req->session()->get('quantities');

    // Log or var_dump the updated quantities
    var_dump('Updated Quantities in Session:', $updatedQuantities);

    // Your existing code for processing the quantities and creating the order
    // Retrieve all categories with their products and the products' inventories
    $categories = Category::with(['products.inventories'])->get();

    $orderItems = [];
    $categoryTotals = [];

    foreach ($categories as $category) {
        foreach ($category->products as $product) {
            // Check if the product ID exists in the session and has a quantity (even if null)
            foreach ($updatedQuantities as $quantityData) {
                if ($quantityData['productid'] == $product->id) {
                    $quantity = $quantityData['quantity'];
                    $orderItems[] = [
                        'category' => $category->category_name,
                        'product_name' => $product->product_name,
                        'quantity' => $quantity
                    ];

                    if (!isset($categoryTotals[$category->category_name])) {
                        $categoryTotals[$category->category_name] = 0;
                    }
                    $categoryTotals[$category->category_name] += (int) $quantity;
                }
            }
        }
    }

    // Log or var_dump the final order items and category totals
    var_dump('Final Order Items:', $orderItems);
    var_dump('Category Totals:', $categoryTotals);

    // Insert the order items into the database
    foreach ($orderItems as $orderItem) {
        DB::table('requestorder')->insert([
            'family_id' => $familyId,
            'category' => $orderItem['category'],
            'categoryTotal' => $categoryTotals[$orderItem['category']],
            'requestedItem' => $orderItem['product_name'],
            'amountNeeded' => $orderItem['quantity'],
            'daterequested' => now()
        ]);
    }

    // Clear the quantities session after order is submitted
    $req->session()->forget('quantities');

here is the blade file

             <h4>Order Section</h4>
<section>
  <div class="row">
     <div class="col-12">
           <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Order Section</h4>
                            </div>          
                            <div class="card-body family-demo-scrollbar">
                                <div class="table-responsive ">
                                <table id="example" class="display" style="min-width: 845px;">
                                 <thead>
                                 <tr>
                                    <th>AVALIABILITY</th>
                                    <th>STATUS</th>
                                    <th>CATEGORY</th>
                                    <th>ITEM NAME</th>
                                    <th>REQUESTED</th>
                                    
                                  </tr>
                                </thead>
                                  <tbody>
                               @foreach($fetchInventoryData as $data)
                               @foreach($data->products as $product)
                               @foreach($product->inventories as $inventory)
                              <tr>
                                <td>{{$inventory->avaliability}}</td>
                                <td style="color: {{ $inventory->status === 'IN STOCK' ? 'green' : 'red' }};">{{ $inventory->status }}</td>

                                

                                <td>{{ $data->category_name }}</td>
                               
                                <td>{{ $product->product_name }}</td>
                                
                                <td>
                              
                                  <!--  <input type="number" name="" id="" min="0" class="form-control"> -->
                                  <input type="number" name="quantity[{{$product['id']}}]" id = "quantity" min="0" class="form-control" >
                                  
                                </td>
                               

                                
                              </tr>
                              @endforeach
                               @endforeach
                               @endforeach
                               </tbody>

                              <tfoot>
                                            <tr>
                                                <th>AVALIABILITY</th>
                                                <th>STATUS</th>
                                                <th>CATEGORY</th>
                                                <th>ITEM NAME</th>
                                                <th>REQUESTED</th>
                                                

                                            </tr>
                                        </tfoot>
                                    </table>
                                    <br><br>
                                </div>
                            </div>
             </div>
        </div>
    </div>
</section>

Issue Details:

dd($req->session()->get('quantities')) shows only the most recent quantities. Session values for previously searched products or categories are lost. Questions:

Why does the session not retain all quantities entered across different searches? How can I persist all quantities entered for different products or categories within the same view? Additional Information:

I’ve verified that the session folder has the correct permissions. Using var_dump() to inspect session data confirms that only the most recent data is stored. I appreciate any guidance or suggestions on how to resolve this issue.

here is a pic of what my order form looks like image of what my order form looks like

0

Browse other questions tagged or ask your own question.