есть трейт создания session_id
trait SessionTrait
{
protected function getUserSessionIdFromCookies(){
if (isset($_COOKIE['session_id']))
$session_id = $_COOKIE['session_id'];
else{
setcookie('session_id', substr(bin2hex(random_bytes(26)), 0, 26), time() + 3600*24*30*365);
}
return $session_id;
}
}
и трейт работы с корзиной
<?php
namespace App\Traits;
use App\Models\Cart;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
trait CartTrait
{
use SessionTrait;
private $data = array();
public function getProducts(){
$product_data = array();
$cart_query = Cart::where('session_id','=', $this->getUserSessionIdFromCookies())->get();
foreach ($cart_query as $cart) {
$stock = true;
$product_query = DB::table('products as p')
->leftJoin('product_descriptions as pd','pd.product_id','=', 'p.id')
->select('p.*','pd.name')
->where('p.id','=', $cart->product_id)
->where('pd.language_id','=', 1)
->where('p.published','=', 1)->first();
if ($product_query && ($cart['quantity'] > 0)) {
$price = $product_query->price;
$old_price = $product_query->old_price;
// Stock
if (!$product_query->quantity || ($product_query->quantity < $cart->quantity)) {
$stock = false;
}
$product_data[] = array(
'cart_id' => $cart->cart_id,
'product_id' => $product_query->id,
'name' => $product_query->name,
'quantity' => $cart->quantity,
'total' => $price * $cart->quantity,
'shipping' => $product_query->shipping,
'image' => $product_query->image,
);
} else {
$this->remove($cart->d);
}
}
return $product_data;
}
public function addProductToCart($product_id){
$cart = Cart::where('session_id','=', $this->getUserSessionIdFromCookies())
->where('product_id','=', $product_id)->first();
if ($cart){
$cart->update([
'quantity' => $cart->quantity + 1
]);
}else{
$cart = new Cart();
$cart->user_id = 0;
$cart->product_id = $product_id;
$cart->session_id = $this->getUserSessionIdFromCookies();
$cart->save();
}
return $cart->quantity;
}
public function countProducts() {
$product_total = 0;
$products = $this->getProducts();
foreach ($products as $product) {
$product_total += $product['quantity'];
}
return $product_total;
}
}
при добавлении товара в корзину проверяю, существует ли $_COOKIE['session_id'], если нет, то записываем
в корзину добавляется один session_id
потом в провайдере AppServiceProvider
делаю так
View::composer(['layouts.tpl.header'], function ($view){
$view->with([
'mini_cart_total' => $this->countProducts(),
]);
});
и выдает другое значение куки