Files
tehnobox/app/Http/Controllers/Shop/CartController.php
ssww23 0ee9f05416
Some checks failed
Deploy / deploy (push) Has been cancelled
1
2026-03-17 01:59:00 +03:00

107 lines
3.3 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Http\Controllers\Shop;
use App\Http\Controllers\Controller;
use App\Models\Product;
use Illuminate\Http\Request;
class CartController extends Controller
{
public function index()
{
$cart = (array) session()->get('cart', []);
$products = Product::query()
->whereIn('id', array_keys($cart))
->where('is_active', true)
->with('category')
->get()
->keyBy('id');
$items = collect($cart)
->map(function ($quantity, $productId) use ($products) {
$product = $products->get((int) $productId);
if (!$product) {
return null;
}
$qty = max(1, (int) $quantity);
return [
'product' => $product,
'quantity' => $qty,
'subtotal' => (float) $product->price * $qty,
];
})
->filter()
->values();
return view('shop.cart', [
'items' => $items,
'itemsCount' => $items->sum('quantity'),
'total' => $items->sum('subtotal'),
]);
}
public function add(Product $product)
{
if (!$product->is_active || $product->stock < 1) {
return back()->with('status', __('Товар сейчас недоступен для заказа.'));
}
$cart = (array) session()->get('cart', []);
$current = (int) ($cart[$product->id] ?? 0);
if ($current >= $product->stock) {
return back()->with('status', __('В корзине уже максимальное доступное количество.'));
}
$cart[$product->id] = $current + 1;
session()->put('cart', $cart);
return back()->with('status', __('Товар ":name" добавлен в корзину.', ['name' => $product->name]));
}
public function update(Request $request, Product $product)
{
$validated = $request->validate([
'quantity' => ['required', 'integer', 'min:1', 'max:99'],
]);
$cart = (array) session()->get('cart', []);
if (!isset($cart[$product->id])) {
return back();
}
$available = max(0, (int) $product->stock);
$quantity = min((int) $validated['quantity'], $available);
if ($quantity < 1) {
unset($cart[$product->id]);
session()->put('cart', $cart);
return back()->with('status', __('Товар ":name" удален из корзины.', ['name' => $product->name]));
}
$cart[$product->id] = $quantity;
session()->put('cart', $cart);
$message = $quantity < (int) $validated['quantity']
? __('Количество ограничено текущим остатком.')
: __('Количество товара обновлено.');
return back()->with('status', $message);
}
public function remove(Product $product)
{
$cart = (array) session()->get('cart', []);
if (isset($cart[$product->id])) {
unset($cart[$product->id]);
session()->put('cart', $cart);
}
return back()->with('status', __('Товар ":name" удален из корзины.', ['name' => $product->name]));
}
}