One option is store in session.
Persisting Form Data Across Page Loads in Laravel
I'm working on an order section in my Laravel application where users can search for categories and add quantities to products. However, sometimes when I search for a category, the selected products and their quantities are lost when I search for different categories . I want to ensure that the form data (quantities) is remembered before submission. Here's my current html code
<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>
so if I use the search search feature and search for BABY category I see what items are avaliable and what i want to add quantities too but as soon as i search another category everything i seleted from baby disappers and it is as if i never selected it
any ideas
@jlrdw how do I do that ?
$request->session()->put('key', 'value');
$value = $request->session()->get('key');
i tried this in my controller
// Store selected quantities in the session before proceeding
$existingQuantities = $req->session()->get('quantities', []);
$newQuantities = $req->input('quantity', []);
// Update the existing quantities with the new ones, ensuring no previous selections are lost
$mergedQuantities = array_replace($existingQuantities, $newQuantities);
$req->session()->put('quantities', $mergedQuantities);
// For debugging purposes: Check the contents of the session
dd($req->session()->get('quantities'));
// 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) {
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;
}
}
}
// Optional: Log or dump the order items and category totals for debugging
// dd('Order Items:', $orderItems);
// dd('Category Totals:', $categoryTotals);
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');
the dd result
19 => null
22 => null
25 => null
26 => null
28 => null
30 => null
34 => null
37 => null
24 => "7"
31 => "7"
it only show the quantities for the last two items or from the last two categories
@Danny971 is this:
$newQuantities = $req->input('quantity', []);
supposed to be quantities?
Edit:
Short example:
$cat1 = ["oranges", "apples"];
$cat2 = ["milk", "cheese"];
Session::push('cat', $cat1);
Session::push('cat', $cat2);
dd(Session::get('cat'));
Gives:
array:2 [▼ // app\Http\Controllers\ArrayController.php:1444
0 => array:2 [▼
0 => "oranges"
1 => "apples"
]
1 => array:2 [▼
0 => "milk"
1 => "cheese"
]
]
Also the session facade is easier to use:
use Illuminate\Support\Facades\Session;
Also an excellent answer form @MichalOravec can be found here:
https://laracasts.com/discuss/channels/general-discussion/update-session-array?page=1&replyId=625450
Here just playing around with an order:
$order = [
[
"productid" => "1",
"quantity" => "5",
],
[
"productid" => "11",
"quantity" => "2",
]
];
Session::put('order', $order);
$neworder = Session::get('order');
for ($i = 0; $i < count($neworder); $i++) {
echo $neworder[$i]["productid"] . " : " . $neworder[$i]["quantity"] . "<br>";
}
echo "=================================" . "<br>";
for ($i = 0; $i < count($neworder); $i++) {
if ($neworder[$i]["productid"] == 11) {
$neworder[$i]["quantity"] = 12;
}
}
Session::put('order', []);
Session::put('order', $neworder);
$neworder = Session::get('order');
for ($i = 0; $i < count($neworder); $i++) {
echo $neworder[$i]["productid"] . " : " . $neworder[$i]["quantity"] . "<br>";
}
die;
Output
1 : 5
11 : 2
=================================
1 : 5
11 : 12 // Updated quantity here was 2.
But go with @michaloravec answer he's real good at this stuff.
@jlrdw $newQuantities = $req->input('quantity', []);
yes this quantities
@Danny971 Did you look over examples.
@Danny971 also to simply add another product to original order:
$order = [
[
"productid" => "1",
"quantity" => "5",
],
[
"productid" => "11",
"quantity" => "2",
]
];
Session::put('order', $order);
$added = [
"productid" => "157",
"quantity" => "1",
];
Session::push('order', $added);
dd(Session::get('order'));
Which of course gives:
array:3 [▼ // app\Http\Controllers\ArrayController.php:1461
0 => array:2 [▼
"productid" => "1"
"quantity" => "5"
]
1 => array:2 [▼
"productid" => "11"
"quantity" => "2"
]
2 => array:2 [▼
"productid" => "157"
"quantity" => "1"
]
]
You need to take some time and get familiar with working with arrays in the session.
Tip, do an array first with put, otherwise you get an extra nested level.
But learn this stuff.
Edit:
- Change a quantity then recreate the session
- Adding a product then just push.
It is that easy.
how can your quantity be anything other than zero when you don't set a value?
@Snapey I set the quantities the application to regard the last category I selected from
I think you should consider using javascript to do your searching instead, or perhaps livewire.
@Tray2 I was trying to get OP to look at the example from @michaloravec which should solve the problem.
@jlrdw That is a very clean approach, and would definatly solve the issue.
@Tray2 can you verify something, I believe @michaloravec solution overrides the session with just one item, would this be better for an updated quantity?
$neworder = Session::get('order');
for ($i = 0; $i < count($neworder); $i++) {
if ($neworder[$i]["productid"] == 11) {
$neworder[$i]["quantity"] = 12;
}
}
Session::put('order', []);
Session::put('order', $neworder);
dd(Session::get('order'));
Giving
array:2 [▼ // app\Http\Controllers\ArrayController.php:1505
0 => array:2 [▼
"productid" => "1"
"quantity" => "5"
]
1 => array:2 [▼
"productid" => "11"
"quantity" => 12 // new quantity added //
]
]
When I tested his it gave a new session array with only one product. I didn't test last night.
@jlrdw I did a simple test of @michaloravec code with just a simple array.
$products = [
[
'productid' => 10,
'quantity' => 11
],
[
'productid' => 11,
'quantity' => 12
]
];
$productId = 10;
foreach ($products as $product) {
if ($product['productid'] === $productId) {
$product['quantity'] = 10;
}
}
var_dump($products);
And it didn't update my array as I think it should have
array(2) {
[0]=>
array(2) {
["productid"]=>
int(10)
["quantity"]=>
int(11)
}
[1]=>
array(2) {
["productid"]=>
int(11)
["quantity"]=>
int(12)
}
}
Your solution
$products = [
[
'productid' => 10,
'quantity' => 11
],
[
'productid' => 11,
'quantity' => 12
]
];
$productId = 10;
for ($i = 0; $i < count($products); $i++) {
if ($products[$i]['productid'] == 10) {
$products[$i]['quantity'] = 10;
}
}
var_dump($products);
Gives the correct result from what it seems.
array(2) {
[0]=>
array(2) {
["productid"]=>
int(10)
["quantity"]=>
int(10)
}
[1]=>
array(2) {
["productid"]=>
int(11)
["quantity"]=>
int(12)
}
}
@Tray2 You are right.
I never actually test the code I provide here on the forum. (The original code was just copied from the OP.)
The main idea in that thread was re-updating the session variable.
@MichalOravec Thanks for the reply.
I believe OP Has enough Information now from this post to solve it.
@Tray2 Thank you for the double check.
@jlrdw No problem
@jlrdw @michaloravec @tray2 @snapey I tried all the examples and I still get undesired results
here is the results
"New Quantities from Request:" // app/Http/Controllers/RequestInsertController.php:364
array:10 [▼ // app/Http/Controllers/RequestInsertController.php:364
19 => null
22 => null
25 => null
26 => null
28 => null
30 => null
34 => null
37 => null
24 => "3"
31 => "3"
]
@Danny971 Just practice. The examples were good. Make sure you are getting the data correctly from the request.
Use your network tab. Look at the request and response.
Learn how to use these troubleshooting tools.
You are familiar with the browser developer tools correct?
@Danny971 Just a tip, I would store the items in the database rather then the session.
@Danny971 also, you have
$newQuantities = $req->input('quantity', []);
But which product.
Can you put this project on Github so we can look at it better.
I think you are missing data in the request.
See @tray2 Current answer as well. I don't believe you have understood the examples well enough. Changing a quality you have to override the entire session array, the array_replace would work, but not if you have missing data.
@Tray2 well I they have to be stored in a database but when I go about to submit to the db some of the items I selected are not being sent
@Danny971 You store the cart in a carts table every time you add something to the cart, this is quite easy using for example livewire, and then when the customer checks out then you create the order.
This one covers exactly that. https://laracasts.com/series/build-a-web-shop-from-a-z
@Danny971 also, you are using array_replace.
If adding another item you use push:
$order = [
[
"productid" => "1",
"quantity" => "5",
],
[
"productid" => "11",
"quantity" => "2",
]
];
Session::put('order', $order);
$orderadd = [
"productid" => "157",
"quantity" => "90"
];
Session::push('order', $orderadd);
dd(Session::get('order'));
Gives:
array:3 [▼ // app\Http\Controllers\ArrayController.php:1461
0 => array:2 [▼
"productid" => "1"
"quantity" => "5"
]
1 => array:2 [▼
"productid" => "11"
"quantity" => "2"
]
2 => array:2 [▼
"productid" => "157"
"quantity" => "90"
]
]
What you do with the array is different when adding to verses changing a quantity.
Again the examples do work, you just need to practice them.
I suggest slow down and make a "play controller" that you can use for practice.
@jlrdw my question is why is it getting some (from the last category ) but not those from previous categories I selected ?
this code
$newQuantities = $req->input('quantity', []);
is to get the quantities from
<input type="number" name="quantity[{{$product['id']}}]" id = "quantity" min="0" class="form-control" >
@Danny971 Again use your network to help troubleshoot. Use less code till you figure out what isn't working. That's what got me through many projects, the developer tools built into firefox.
View some videos, @jeffreyway is always using the network tab and the console log tab.
By less code, meaning comment out some and troubleshoot smaller chunks at a time.
@jlrdw its not about changing a quantity. say for example I search for bedding category and see the list of products avaliable under that category . when I go to add the quantity request for a product and then search for another category then the previous one bedding in this example is lost
@Danny971 Look at @jeffallen reply, that might be a good idea to look at some existing shoping carts and study how they handle this.
I know myself, but it's hard to explain everything in a forum answer.
Or use @tray2 idea and watch that video series, or both.
Do you have a "Go to Cart" setup? Normally you can change quantity in the cart before checkout.
Implement @tray2 idea of storing in the database since you are having problems using session.
Edit:
Look at this one: https://github.com/darryldecode/laravelshoppingcart
A little older but you might get some ideas.
@jlrdw if I understand correctly you use push to add more items to the array ?
Why not look at a Github shopping carts based on Laravel and look at the code they used. You will probably gain some insight of how to handle the cart.
I hosted an image on github so yall could have an idea how my order form is
its not an add to cart feature
https://github.com/DannyAntoine/testimage/blob/main/orderscreen.JPG
@Danny971 Store orders in a table. Is this an app where a user is ordering from you? Or an app where you are ordering more stock?
You could also look over Github for some inventory packages.
@jlrdw its not like the way you think. lets say I have a case I personally place the order the client ask for the in stock or out of stock is to have a visual display so I know what I have avaliable when processing an order
@jlrdw so in the image you have seen under the requested column with the input field is where i enter the amount the client needs
@Danny971 then it would be saved in an invoice (or orders if you prefer) table. Once fulfilled you close out the invoice. A boolean field would work.
Some basic business and bookkeeping lessons would help you understand this a lot more.
Edit:
I don't understand Persisting Form Data Across Page Loads when just entering orders?
I don't see where you use multiple pages (forms) for this.
@jlrdw its a multi-step form. your statement " it would saved in an invoice (or orders if you prefer) table". thats what I originally want but due to the fact that it is not saving all or remembering the different product i selected by category it is not so I I search appliances and selected three items there and then search for bedding and selet four product there and if finally I selected kitchen category I search and select two product there it will only remember the quantities for the last category and save that and not the one before. so this is why I wanted to use the session to help remember those decesions
@Danny971 the session would save the data, and before saving to database get the data from session.
It's hard to troubleshoot an app from a forum, without having the whole app.
You have everything you need, just implement it tn the correct way.
Again use your network tab to troubleshoot.
@jlrdw do you want to do a discord meeting with me I could share my screen and you could help me from there. here is a link to my server https://discord.gg/cNejXujE
i can share my screen and you could help me debug it more
@Danny971 sorry, I don't do that. But if you put the whole project on Github I and others could have a look.
@jlrdw not just the relavant code ?
@jlrdw it would be easier to put the relavant code here
@Danny971 you can try, but that's a lot of code for a forum, maybe just put prevalent code on Github. Are you using ajax in your code?
Edit:
Are you using flags to just pull low stock?
Edit:
It's been a while, but in the past I used a db trigger.
@jlrdw that why I wanted to put the relavant code
I debugging using the network tabe just checking the paylod
and it the same thing
the last category I selected from is only being submited and the previous ones null
here is my controller
that manages that part of the application
$existingQuantities = $req->session()->get('quantities', []);
$newQuantities = $req->input('quantity', []);
// Log the incoming quantities
Log::info('New quantities:', $newQuantities);
Log::info('Existing quantities:', $existingQuantities);
$mergedQuantities = array_merge($existingQuantities, $newQuantities);
// Log the merged quantities
Log::info('Merged quantities:', $mergedQuantities);
$req->session()->put('quantities', $mergedQuantities);
// After merging, log the session data
Log::info('Quantities in session after put:', $req->session()->get('quantities'));
// Rest of your code...
// 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) {
if (isset($mergedQuantities[$product->id]) && $mergedQuantities[$product->id] > 0) {
$quantity = $mergedQuantities[$product->id];
// Log each product being added to orderItems
Log::info('Adding product to order:', [
'category' => $category->category_name,
'product_name' => $product->product_name,
'quantity' => $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] += $quantity;
}
}
}
// Log the final order items and category totals
Log::info('Final order items:', $orderItems);
Log::info('Category totals:', $categoryTotals);
// Insert into the database and log each insertion
foreach ($orderItems as $orderItem) {
Log::info('Inserting order item:', $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 and log the action
$req->session()->forget('quantities');
Log::info('Session cleared after order submission.');
here is the html
<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>
@Danny971 after
$existingQuantities = $req->session()->get('quantities', []);
show a dd
dd($existingQuantities);
Then comment that:
//dd($existingQuantities);
then:
dd($newQuantities);
then show a dd of:
dd($mergedQuantities);
comment that and show a dd of
dd($req->session()->get('quantities');
If the array levels aren't the same, that's the problem.
Or you are mixing a regular array and a json array.
Data has to be consistent.
edit:
When I use array_merge the result is wrong.
I get
array:4 [▼ // app\Http\Controllers\ArrayController.php:1459
0 => array:2 [▼
"productid" => "1"
"quantity" => "5"
]
1 => array:2 [▼
"productid" => "11"
"quantity" => "2"
]
"productid" => "157"
"quantity" => "90"
]
now compare to answer I gave earlier:
result after dd($existingQuantities);
[]
an empty array
and after dd($newQuantities);
67 => null
103 => null
111 => null
114 => null
116 => null
110 => "5"
104 => "5"
107 => "5"
102 => "5"
106 => "5"
]
the result of dd($mergedQuantities);
array:10 [▼ // app/Http/Controllers/RequestInsertController.php:370
0 => null
1 => null
2 => null
3 => null
4 => null
5 => "5"
6 => "5"
7 => "5"
8 => "5"
9 => "5"
]
the result of dd($req->session()->get('quantities'));
array:10 [▼ // app/Http/Controllers/RequestInsertController.php:418
0 => null
1 => null
2 => null
3 => null
4 => null
5 => "5"
6 => "5"
7 => "5"
8 => "5"
9 => "5"
]
@Danny971 so no $existingQuantities? Should there be?
and did you see where I mentioned to compare array_merge verses push, see my edited answer above. https://laracasts.com/discuss/channels/laravel/persisting-form-data-across-page-loads-in-laravel?page=1&replyId=944301
Also show how you add to session to 'quantities'. Also show a dd right after putting it in session. And show the data. Somehow it's not saving to session.
Check storage, is it there?
Edit:
And if checking storage sessions, a dd messes with session, so use a var_dump.
@jlrdw I check the laravel logs it's not there the issue is in the controlller im getting closer to solving it
@Danny971 Check permissions for that folder. Make sure it can be written to.
@jlrdw i tried this
// 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');
you mean the storage folder
drwxrwxr-x 5 www-data www-data 4096 Feb 18 02:05 storage
@Danny971 The session information should be in there.
Comment out $req->session()->forget('quantities'); and test.
@jlrdw in the laravel.log ?
@Danny971 what? Comment that line out in your code and look for sessions in the sessions folder. If they are not there sessions aren't being written.
@jlrdw in the sessions folder this is what i see
/var/www/html/storage/framework/sessions$ ls
0L1aI4JkRAAU4bbhketGsVyBxLr19gL8t0U64Yvb 9G2iAJQiTadcwLD07DiLkLnSsdFgQXteqzCotgbI NrEHoB1ojvwDA2A4bYcsmr9Xum2mSBx9dQfxVLlO at1mRaJhCtMmb9Jh8HLxLVhUDFnYTLdWZuI1XNYu mwB96T5Oludsch0PZgp6gAwCxHEeI6Dow3K51bbv
3xa5quEWBYjDM9csPdqhvK8pThRMlXZzZ1FWMAJ1 DKmvKSVRF0fFiusPwajkPgCodIcyDEgZxVBzpZYp PP140BhrgkmPCAO7YnCByKaqpZKuD9yw71zgkN22 d975JFV7XaM4W00yabYgpZ7dqZEM0iKORIZh2Cqz rU9VMlgEWmLEnnixx8UVH1etNRoT9D39w57Efd20
6FfJYuTe4NP3uF0llyWOdkxMTe3tJecanPLwYwa9 F0wBEN7L34MqiSzLDAL9oRQObyGe2iL6Age5m5Oe Qxnme1dOdPZmqbN92iWLsI3M8W3zgRurIzdwXjl4 dYw1hIFnT2vdpCxTNzEra1CstXcaU8oYHjlHaRds scqgr5irYKgzvMmL8acUDaITN0kg8IjiznwzOAl8
7VPSvKdhLQZv8Sr3RB2IS885NRwwKLm3tW5QkstB MvGlJTET18oY5FRcSo7tfMWgzYYlxHv85xEmlH0j TLF579GVsuoqYKPtO6P5fuNrAuWfHdxvZyMrZgIL hZXzvDcaTD2AUqDxxa3xjJ177QhATjC2SbLd313l uWHLIo1f6NoIaXGqojIXBUJWoy3qnpoDiqKZFUCg
8iODHGcjcRFUVou3I6BHjvhFoiad7cHUp6uCYbMu NI7as3ESaXX1xXRdRZvgBNn7ninHiP7uIKpJFTYh U9i7M1da1yAXWJz9MCFvHOEiQTHUUuZ2ewnppePv li5UWu2uBOCLbtTrM2M805YfdfCm3QnKoRqtCArq zlsiHlLBcvDefVyDjH07om7UI4iKBDQr063INvpd
8oGKz8gk2W9Opnl2b7kXwViv3G6L2sFqVGya5wHu NMfh8CQMsBWtjtXOAiOnPf57DIQGJOaT7wjpjoeF Y83AhUcAvgTnVBBc0eXr3TwyRPFqYLlsnwvmW1Co m7FouI9e8CcgQ7eD0kcJ145gVc5x7Lo1i94Z2wn3 zsUjDA7TlESGe8uxCZw6kG1KYoOW3S0ocyXzeADB
@Danny971 Session is working, so how come when you store the data in session it's not working show the code that you use to store data in session.
Also delete sessions and store one Item. And have a look to make sure it's correct.
@jlrdw already did thats the controller code
// 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');
it the same as the above code i used in the actual code I did commented out $req->session()->forget('quantities');
@Danny971 you have this:
$existingQuantities = $req->session()->get('quantities', []);
But where are you putting this into the session? I do not see any original data being written to the session. That's why you get null.
Edit:
A inventory system shouldn't be this difficult. I urge you to look at some on Github to get a better idea.
Edit:
Study this close:
If I have an original session data of this:
$order = [
[
"productid" => "1",
"quantity" => "5",
],
[
"productid" => "11",
"quantity" => "2",
]
];
Session::put('order', $order);
// add this
$orderadd = [
"productid" => "157",
"quantity" => "90"
];
Session::push('order', $orderadd);
// and
echo "<pre>";
print_r(Session::get('order'));
I get this:
Array
(
[0] => Array
(
[productid] => 1
[quantity] => 5
)
[1] => Array
(
[productid] => 11
[quantity] => 2
)
[2] => Array
(
[productid] => 157
[quantity] => 90
)
)
You never put initial data in session.
You have been given examples, but you keep doing your code the same way.
If you ask for help, then study the answers people give you.
Also you mentioned users, so that would be a shopping cart.
So are you doing inventory or do you have customers shopping?
@jlrdw I used the session::push here is my code the result is the same
// Retrieve existing quantities from the session
$existingQuantities = $req->session()->get('quantities', []);
// Loop through the new quantities provided by the user
foreach ($req->input('quantity', []) as $productId => $quantity) {
// Create an array with product ID and its corresponding quantity
$quantityData = [
'productid' => $productId,
'quantity' => $quantity
];
// Check if the product already exists in the session
$found = false;
foreach ($existingQuantities as &$existingQuantity) {
if ($existingQuantity['productid'] == $productId) {
// Update the quantity for the existing product
$existingQuantity['quantity'] = $quantity;
$found = true;
break;
}
}
// If the product is not found, push the new product and quantity into the session
if (!$found) {
Session::push('quantities', $quantityData);
} else {
// If the product is found, replace the session data with the updated array
Session::put('quantities', $existingQuantities);
}
}
// Output session data for debugging
echo "<pre>";
print_r(Session::get('quantities'));
here is the results
Array
(
[0] => Array
(
[productid] => 54
[quantity] =>
)
[1] => Array
(
[productid] => 55
[quantity] =>
)
[2] => Array
(
[productid] => 45
[quantity] => 2
)
[3] => Array
(
[productid] => 48
[quantity] => 2
)
[4] => Array
(
[productid] => 44
[quantity] => 2
)
[5] => Array
(
[productid] => 53
[quantity] => 22
)
[6] => Array
(
[productid] => 47
[quantity] => 2
)
[7] => Array
(
[productid] => 51
[quantity] => 2
)
[8] => Array
(
[productid] => 42
[quantity] => 22
)
[9] => Array
(
[productid] => 50
[quantity] => 2
)
[10] => Array
(
[productid] => 43
[quantity] => 22
)
[11] => Array
(
[productid] => 49
[quantity] => 2
)
[12] => Array
(
[productid] => 46
[quantity] => 22
)
[13] => Array
(
[productid] => 52
[quantity] => 2
)
)
the ones with a quantity are from the last category I selected from
the first two with with null quantity was from another category and its not only two items I selected I selected 13 items but it shows as it's two and no quanttiy shown
@Danny971 look at your first lines of code:
// Retrieve existing quantities from the session
$existingQuantities = $req->session()->get('quantities', []);
You are not showing the code where these are put into session.
Edit:
Also the :
get('quantities', [])
Adds an extra level: just:
get('quantities')
But again you are not getting anything there.
isnt that the code
// If the product is not found, push the new product and quantity into the session
if (!$found) {
Session::push('quantities', $quantityData);
} else {
// If the product is found, replace the session data with the updated array
Session::put('quantities', $existingQuantities);
}
@Danny971 it was a shortcut, meaning:
$existingQuantities = $req->session()->get('quantities');
But you get nothing here, where is that data coming from?
Edit:
Since you are having trouble with this why not just use database.
Insert first then update as needed.
A server fetched partial would / could work to show the products selected.
Or just blade.
@jlrdw I know it was a shortcut and thats exactly what I tried
$existingQuantities = $req->session()->get('quantities');
@jlrdw nah I will keep on trying I will figure it out eventually
well that my goal is to send it to a table in the database but it doesnt catch all the item requested that why im using the sessions
@Danny971 It would still be good if you put the project on Github to get more help.
I still don't see where you are putting the first set of data in session.
@jlrdw by first set of data do you mean the first section of the multi step form ? if so then no I did not put them into session I only put this section in session which is the third step. based on what you are trying to tell me could you talior my code to actually accomplish this
like to put this into session
// Retrieve existing quantities from the session
$existingQuantities = $req->session()->get('quantities', []);
@Danny971 try:
if ($req->session()->has('quantities')) {
$req->session()->push('quantities', $newQuantities); // other times
} else{
$req->session()->put('quantities', $newQuantities); // first time
}
Comment out this"
//$existingQuantities = $req->session()->get('quantities', []); // comment out
And all that merge stuff comment out, use session like this, checking if round one (first session put) was already done.
Try it then show new print_r output.
I hope you understand do this after your getting the $newQuantities = $req->input('quantity', []); And why the brackets?
@jlrdw your code is much neater but i get the same result when i implement it
what if I tried this
<input type="number" name="quantity[{{ $product['id'] }}]" id="quantity" min="0" class="form-control" value="{{ old('quantity.' . $product['id']) }}">
in the blade file using the old helper function
@Danny971 Are your inputs an array?
@Danny971 Tested this works.
$data = $req->except('_method', '_token');
if (Session::has('order')) {
echo "adding to order";
Session::push('order', $data);
} else {
echo "first time";
Session::put('order', [$data]);
}
Session::get('order');
echo "<pre>";
print_r(Session::get('order'));
adding to order
Array
(
[0] => Array
(
[productid] => 1
[quantity] => 1
)
[1] => Array
(
[productid] => 2
[quantity] => 2
)
[2] => Array
(
[productid] => 100
[quantity] => 5
)
[3] => Array
(
[productid] => 15
[quantity] => 25
)
)
You can figure out sorting.
@jlrdw yeah i store it in an array
@Danny971 The point was did you notice the extra brackets when I did first time.
Do you have this solved yet?
@Snapey will do.
@Snapey nope
@Snapey just cause I have difficultites solving an issue doen't mean I am going to change my carrer
@jlrdw going to try a state management library (vuex).
I think the problem lies in the way im managing product quantities when searching for different categories. im overwriting the quantities for each search instead of preserving them
@Danny971 again, without seeing all the code it's hard to troubleshoot someone else's project.
You only showed portions.
But the last code I showed you works from a blade file being posted.
@jlrdw going to post it on git hub
@jlrdw here is the github link
https://github.com/DannyAntoine/testcfr/tree/master
the code im haveing issues with is in the RequestInsertController.php
@Danny971 a lot of controllers, so which controller is:
$existingQuantities = $req->session()->get('quantities', []);
located in and what view goes with it? I don't want to search all through the code.
I also suggest you take the lessions:
https://laracasts.com/series/30-days-to-learn-laravel-11
You aren't even using validation.
@Danny971 you seriously need to learn how to make Laravel work for you and simplify your code. Using post superglobal ? This isnt 2010.
@jlrdw the view is requestform.blade.php and the controller is RequestInsertController.php
@Snapey thanks for your feedback and I will
@Danny971 I gave an example here:
That shows how do put and push correctly.
You don't seem to modify your code to work correctly.
And yes I looked over the code. Please take the free training from @jeffreyway.
Also view some lessons on refactoring code.
Edit:
If you are using javascript for part of this, you have to pass data to a view for ajax / javascript via json.
I suggest you install a free shopping cart and play with it to learn how the cart sessions work.
But again your code needs a refactor, my suggestion.
@jlrdw thanks
@jlrdw one favor could you modify the section of my code so I can see how it is done
that where i received the quantities for each product could you modify the code for me
the controller code to handle it
@Danny971 I showed that here:
Also learn to experiment, test, and some trial and error to work out problems.
Please take the free training.
There are free videos on
- php
- laravel
- javascript
- etc.
@jlrdw with the code you gave me I tested it out and got some new results. I feel the problem isnt with the controller it might me with the html and js
$newQuantities = $req->except('_method','_token');
// Loop through the new quantities provided by the user
foreach ($newQuantities as $productId => $quantity) {
// Ensure the quantity is valid (not null or empty)
if ($quantity !== null && $quantity !== '') {
// Prepare the data to be stored in the session
$quantityData = [
'productid' => $productId,
'quantity' => $quantity
];
// Check if the 'order' session exists
if (Session::has('order')) {
// Add the new product quantity to the existing order
Session::push('order', $quantityData);
} else {
// Create a new session with the first product quantity
Session::put('order', [$quantityData]);
}
}
}
// Output session data for debugging
echo "<pre>";
print_r(Session::get('order'));
dd("breakpoint");
dd("breakpoint");
i got information from the previous steps of the multi step form
I made some changes to the html and the code works but the user interface is messed up
the issue was with the dataTable
Please or to participate in this conversation.