Home > database >  How many products do I have Laravel
How many products do I have Laravel

Time:01-20

I have a table whit some products and I try to do that if I add more products than I have in my inventory it has to show me an alert.

I did it but its not working, In products i have the sku and reference.In inventories i have all the products that i have.

Controller:

foreach ($request->dataTable as $dataTable) {
    $productId = DB::table('products')
        ->where('sku', $dataTable[2])
        ->whereNull('deleted_at')
        ->select('id', 'reference')
        ->first();
    $inventoryId = DB::table('inventories')
        ->where('product_id', $productId->id)
        ->whereNull('deleted_at')
        ->whereNull('sale_id')
        ->select('id')
        ->first();

    if ($inventoryId == null) {
        return response()->json([
            'type' => 'error',
            'msg'  => 'No existe suficiente stock para realizar la venta del producto con referencia: ' . $productId->reference . '. Solo hay ' . $productId->references->count(),
        ]);
    }
}

Product Model:

public function references()
{
    return $this->hasOne('App\Models\Inventory');
}

Products

id reference sku
1 BCR2214 0108888893016580
2 BCR2219 0108888893016580

Inventories

ID product_id
1 1
2 1
3 2

If I add a product_id = 1 three times it has to show me the alert and says "The product 1 only has 2 in stock in inventory" But I add two products and says: "error", msg: "Undefined property: stdClass::$references"}

CodePudding user response:

You're not able to access eloquent relationships on the DB facade.

If you wanted to access the references relationship you'd need to change

$productId = DB::table('products')
        ->where('sku', $dataTable[2])
        ->whereNull('deleted_at')
        ->select('id', 'reference')
        ->first();

into an eloquent model lookup, something like

$productId = App\Models\Products::where('sku', $dataTable[2])
        ->whereNull('deleted_at')
        ->select('id', 'reference')
        ->first();

As a separate note and to help with performance, I'd also suggest eager loading the inventories relationship. Without knowing much about your DB design, something like the below should get you started

//   Product model
public function inventories()
{
   return $this->belongsTo('App\Models\Inventory');
}

Then you could adjust the top eloquent query to be something like

$productId = App\Models\Products::where('sku', $dataTable[2])
        ->whereNull('deleted_at')
        ->doesntHave('inventories')
        ->select('id', 'reference')
        ->first();

Be sure to checkout Laravel eloquent relationships for more information specific to your situation

  • Related