Answer the question
In order to leave comments, you need to log in
Different in Laravel cookies?
there is a trait of creating 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;
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question