Laravel Session Not Persisting Product Quantities Across Searches

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

New contributor

Dangelo Antoine is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật