Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Danny971's avatar

How to Submit Order with Product and Category Data, Calculate Category Totals, and Store in Database (Laravel)

Hi everyone,

I'm working on a Laravel application where I need to handle order submissions. Here's the core functionality I'm aiming to achieve:

  1. Capture Product Name, Category, and Requested Quantity:

I want to capture the product name, its category, and the number of items requested by the user when submitting an order. 2. Calculate Category Totals:

I need to calculate the total number of items requested for each category. 3. Store Order Data in Database:

The captured product name, category, requested quantity, and calculated category total need to be stored in a database table named requestorder.

here is my 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="requested[{{ $data->category_name }}][{{ $product->product_name }}][quantity]" min="0" class="form-control">
                            <input type="hidden" name="requested[{{ $data->category_name }}][{{ $product->product_name }}][category]" value="{{ $data->category_name }}">
                            <input type="hidden" name="requested[{{ $data->category_name }}][{{ $product->product_name }}][requestedItem]" value="{{ $product->product_name }}">
                                </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>

 
        $categoryTotals = [];

        // Loop through each product's request data to calculate category totals
        foreach ($req->requested as $categoryData) {
            foreach ($categoryData as $itemData) {
                $quantity = $itemData['quantity'];
                $category = $itemData['category'];

                if (!isset($categoryTotals[$category])) {
                    $categoryTotals[$category] = 0;
                }

                $categoryTotals[$category] += $quantity;
            }
        }

        // Insert each requested item into the requestedorder table
        foreach ($req->requested as $categoryData) {
            foreach ($categoryData as $itemData) {
                $quantity = $itemData['quantity'];
                $category = $itemData['category'];
                $requestedItem = $itemData['requestedItem'];
                $dateRequested = Carbon::now(); // Or any other logic for the date requested
                $categoryTotal = $categoryTotals[$category];
               
               
               
               DB::table('requestorder') ->insert([
                 
                    'category' => $category,
                    'categoryTotal' => $categoryTotal,
                    'requestedItem' => $requestedItem,
                    'amountNeeded' => $quantity,
                    'daterequested' => $dateRequested,
                    'family_id' => $familyId,
                ]);
            }
        }
0 likes
15 replies
jlrdw's avatar

I usually fill these on the order form using lookup tables or dropdowns.

I suggest a basic business course (even home study) and some basic bookkeeping.

You can't just fill from relations, things like invoices and orders are their own table saved separately because prices change and so does other things.

Three months later a customer has a problem, you need a way to pull that invoice or order from an orders table. For calculating totals or sums look at example aggregate functions.

jlrdw's avatar

@Danny971 see https://laracasts.com/discuss/channels/eloquent/why-do-we-need-an-invoicelines-table-databasedesign

And

https://laracasts.com/discuss/channels/code-review/amazon-style-product-variationoptions

But search for more as needed. Those two I bookmarked.

Edit:

Are you using the term order and invoice for the same thing.

Also, you can have some payment services track all of this for you. For example, when I recently ordered Malcolm Reflect backup software. An outside company handles all of that refunds the invoice everything.

Of course.That's going to cost a extra.

But all you need is a related table set up with the order or invoice would be the main and the sub table would be the order or invoice details, meaning line items with quantities.

Maintaining your inventory is the complicated part with the pivot tables and all of that.But an invoice should be a fairly straightforward thing.

Danny971's avatar

@jlrdw well I just want to get the category name the product name and the quantity into the db because this my requirements for the project

jlrdw's avatar

@Danny971 I would suggest get price also, because there is no way you can pull up that past invoice correctly if prices change. How would you know what the price was.

Danny971's avatar

@jlrdw no need for prices it's. it's a school project for donations so no need for prices and it creates a pdf file so all the info will be thereon the pdf file

Snapey's avatar

surely your product has an ID? If not, why not.

Surely your product belongs to a category?

So all you really need to store in your order is the id and the quantity?

Danny971's avatar

@Snapey surely your product has an ID? If not, why not. : yes

Surely your product belongs to a category? :yes

So all you really need to store in your order is the id and the quantity? : how do I do that

Danny971's avatar

@Snapey can you help me fix up my code based on your above suggestion

Snapey's avatar

@Danny971 I can't guess at the intent from the way your code is structured. Three nested loops? Just get your data and models in the right shape first.

Danny971's avatar

@Snapey they are in the right shape

Here is the category table

id | category_name | created_at | updated_at

Here is the product table

id | category_id (fk) | product_name | updated_at | created_at

Here is the inventory table

id | avaliability | status | weight | sku | product_id (fk) | area | monetary_value | donated_value | created_at | updated_at

here is what each model looks like

Category Model 

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Products;
class Category extends Model
{
    
    protected $table = 'category';  
    protected $fillable = ['category_name'];
    use HasFactory;

    public function products() {
        return $this ->hasMany(Products::class);
    }
}

Products Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Category;

class Products extends Model
{
    protected $table = 'products';
    use HasFactory;

    protected $fillable = ['product_name', 'category_id'];

    public function category() {
        return $this->belongsTo(Category::class);
    }

    public function inventories()
    {
        return $this->hasMany(Inventory::class,'product_id');
    }
    
}
Inventory model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Products;

class Inventory extends Model
{
    protected $table = 'inventory';

    protected $fillable = [
        'sku',
        'product_id', 
        'created_at',
        'updated_at',
    ];

    // Define the relationship to the Product model
    public function product()
    {
        return $this->belongsTo(Products::class,'product_id');
    }
   
    
    use HasFactory;
}
Danny971's avatar

@jlrdw @snapey what do you think im doing wrong

here is the laravel error log

[2024-06-28 22:19:25] local.INFO: Requested Items: [{"quantity":null,"category":"BATH","requestedItem":"Hangers"},{"quantity":null,"category":"Miscellaneous","requestedItem":"Lamp"},{"quantity":null,"category":"Miscellaneous","requestedItem":"Lg Rug"},{"quantity":null,"category":"Miscellaneous","requestedItem":"Sm Rug"},{"quantity":null,"category":"Miscellaneous","requestedItem":"TV Tray"},{"quantity":null,"category":"Miscellaneous","requestedItem":"Folding table"},{"quantity":null,"category":"Miscellaneous","requestedItem":"Folding chairs"},{"quantity":"1","category":"bedding","requestedItem":"sheet set"},{"quantity":"2","category":"bedding","requestedItem":"Bed Frame"},{"quantity":"3","category":"bedding","requestedItem":"Comforter"}] 
[2024-06-28 22:19:25] local.INFO: Item Data: {"quantity":null,"category":"BATH","requestedItem":"Hangers"} 
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"BATH","requestedItem":"Hangers"}  
[2024-06-28 22:19:25] local.INFO: Item Data: {"quantity":null,"category":"Miscellaneous","requestedItem":"Lamp"} 
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"Lamp"}  
[2024-06-28 22:19:25] local.INFO: Item Data: {"quantity":null,"category":"Miscellaneous","requestedItem":"Lg Rug"} 
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"Lg Rug"}  
[2024-06-28 22:19:25] local.INFO: Item Data: {"quantity":null,"category":"Miscellaneous","requestedItem":"Sm Rug"} 
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"Sm Rug"}  
[2024-06-28 22:19:25] local.INFO: Item Data: {"quantity":null,"category":"Miscellaneous","requestedItem":"TV Tray"} 
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"TV Tray"}  
[2024-06-28 22:19:25] local.INFO: Item Data: {"quantity":null,"category":"Miscellaneous","requestedItem":"Folding table"} 
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"Folding table"}  
[2024-06-28 22:19:25] local.INFO: Item Data: {"quantity":null,"category":"Miscellaneous","requestedItem":"Folding chairs"} 
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"Folding chairs"}  
[2024-06-28 22:19:25] local.INFO: Item Data: {"quantity":"1","category":"bedding","requestedItem":"sheet set"} 
[2024-06-28 22:19:25] local.INFO: Item Data: {"quantity":"2","category":"bedding","requestedItem":"Bed Frame"} 
[2024-06-28 22:19:25] local.INFO: Item Data: {"quantity":"3","category":"bedding","requestedItem":"Comforter"} 
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"BATH","requestedItem":"Hangers"}  
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"Lamp"}  
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"Lg Rug"}  
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"Sm Rug"}  
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"TV Tray"}  
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"Folding table"}  
[2024-06-28 22:19:25] local.ERROR: Quantity key is missing for requested item: {"quantity":null,"category":"Miscellaneous","requestedItem":"Folding chairs"}  
[2024-06-28 22:19:25] local.INFO: Family ID below pdfdata : {"family_id":372} 

jlrdw's avatar
jlrdw
Best Answer
Level 75

@Danny971

Alt image

You derive your order (invoice from your tables via lookup tables or dropdowns.

The order (invoice) gets saved. But you also write the code to update current stock.

Meaning if you sold one widget, then you substract one widget from wherever you store the quantity on hand.

You have main invoice and line items. A one to many relation.

If all you do is sell direct then just issue receipts.

Please or to participate in this conversation.