parfum/app/Traits/Purchase/WithUpdateStock.php
Yoga Pangestu 33e138be42 feat(purchase): implementasi fitur belanja/restock
-membuat relasi polimorfirk
-membuat beberapa trait untuk kebutuhan crud
-dan lainnya tentang implementasi fitur ini
2025-10-04 21:09:20 +07:00

45 lines
1.1 KiB
PHP

<?php
namespace App\Traits\Purchase;
use App\Models\Bottle;
use App\Models\Perfume;
use App\Models\Product;
trait WithUpdateStock
{
public function increaseOutletStock($outlet, $item)
{
$quantity = $item->quantity;
switch ($item->purchasable_type) {
case Perfume::class:
$relation = 'perfumes';
break;
case Product::class:
$relation = 'products';
break;
case Bottle::class:
$relation = 'bottles';
break;
default:
return;
}
$existing = $outlet->{$relation}()
->where("{$relation}.id", $item->purchasable_id)
->first();
if ($existing) {
$currentStock = $existing->pivot->stock ?? 0;
$outlet->{$relation}()->updateExistingPivot($item->purchasable_id, [
'stock' => $currentStock + $quantity,
]);
} else {
$outlet->{$relation}()->attach($item->purchasable_id, [
'stock' => $quantity,
]);
}
}
}