Laravel Session is not storing new items but it's overwriting - laravel

I was trying to add new items to a session container, and if old items are available then I'll just push the new items to the container. Now whenever I'm adding new items it's storing the current item by replacing the previous item, where is the issue?
In Controller my function to add new items
public function addToCart($id)
{
$product = Product::findOrFail($id);
$oldCart = Session::has("cart") ? Session::get("cart") : null;
$cart = new Cart($oldCart);
$cart->addNewItem($id, $product);
Session::put("cart", $cart);
dd(Session::get("cart"));
}
In Class
class Cart
{
public $items = null;
public $totalQty = 0;
public $totalPrice = 0;
public function __construct($oldCart)
{
if ($oldCart) {
$this->items = $oldCart->items;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}
public function addNewItem($id, $item)
{
$storeNewItem["product_id"] = $item->id;
$storeNewItem["product_name"] = $item->product_name;
$storeNewItem["product_price"] = $item->product_price;
$this->totalQty++;
$this->totalPrice += $item->product_price;
$this->items[$id] = $storeNewItem;
}
}

In Cart Class
public function addNewItem($id,$item) {
$storeNewItem["product_id"] = $item->id;
$storeNewItem["product_name"] = $item->product_name;
$storeNewItem["product_price"] = $item->product_price;
$this->totalQty++;
$this->totalPrice += $item->product_price;
return [
'totalQty', => $this->totalQty,
'totalPrice', => $this->totalPrice,
'items[$id]', => $storeNewItem,
]
}
In Controller addToCart Function
$newCart = $cart->addNewItem($id,$product);
Session::put("cart",$newCart );

Related

Laravel 9 Infinite Scroll in Sub Comments

I want to implement infinite scroll in sub comments, but I have no idea what to do. I've tried to push the addition data, but nothing is gonna work.
public function mount($link)
{
$this->link = $link;
$campaign = Campaign::where('status', 1)->where('link', $this->link)->first();
if ($campaign) {
$this->campaignId = $campaign->id;
$this->campaign = $campaign;
$this->comments = new Collection();
$this->subComments = new Collection();
$this->loadFirst();
}
}
public function loadSubData($parentCommentId)
{
$this->perPage++;
$this->comments1 = Comment::orderBy('id', 'desc')->where('campaign_id', $this->campaignId)->cursorPaginate(3, ['*'], 'cursor', Cursor::fromEncoded($this->nextCursor));
$this->comments1->getCollection()->transform(function ($value) use ($parentCommentId) {
$datas = [];
$userComment = User::where('id', $value->user_id)->first();
$countSubComments = SubComment::orderBy('id', 'desc')->where('parent_comment_id', $value->id)->get();
$datas['id'] = $value->id;
$datas['user_id'] = $userComment;
$datas['comment'] = $value->comment;
$datas['updated_at'] = $value->updated_at;
$datas['count_sub_comment'] = count($countSubComments);
$this->subComments1 = SubComment::orderBy('id', 'desc')->where('parent_comment_id', $parentCommentId)->cursorPaginate($this->perPage, ['*'], 'cursor', Cursor::fromEncoded($this->nextCursorSubComment));
$datas['sub_comments'] = $this->subComments1->getCollection()->transform(function ($subValue) {
$datas2 = [];
$userSubComment = User::where('id', $subValue->user_id)->first();
$datas2['id'] = $subValue->id;
$datas2['user'] = $userSubComment;
$datas2['sub_comment'] = $subValue->sub_comment;
$datas2['updated_at'] = $subValue->updated_at;
$datas2['has_more_pages'] = $this->subComments1->hasMorePages();
return $datas2;
});
$this->subComments->push(...$datas['sub_comments']); // problem here
return $datas;
});
}
Actually, is more easier to do infinite scroll in parent comments, just add piece of code below:
public function loadMoreComments()
{
if ($this->hasMorePages !== null && !$this->hasMorePages) {
return;
}
$this->loadAllData();
$this->comments->push(...$this->comments1->items()); // $this->comments1 is new coming data
if ($this->hasMorePages = $this->comments1->hasMorePages()) {
$this->nextCursor = $this->comments1->nextCursor()->encode();
}
}
But it's more tricky when I've tried this in sub comments.
So, the expectation when users click view more comments, loadSubData($id) is called.

Too few arguments to function App\Awe\JsonUtility::addNewProduct(),

i am trying to create a CRUD app and am having trouble, if anyone can point me in the right direction i would be grateful, thank you.
Hi there i am having difficulty using data from the json.
i have used it here and it as worked
class JsonUtility
{
public static function makeProductArray(string $file) {
$string = file_get_contents($file);
$productsJson = json_decode($string, true);
$products = [];
foreach ($productsJson as $product) {
switch($product['type']) {
case "cd":
$cdproduct = new CdProduct($product['id'],$product['title'], $product['firstname'],
$product['mainname'],$product['price'], $product['playlength']);
$products[] = $cdproduct;
break;
case "book":
$bookproduct = new BookProduct($product['id'],$product['title'], $product['firstname'],
$product['mainname'],$product['price'], $product['numpages']);
$products[]=$bookproduct;
break;
}
}
return $products;
}
this is my controller
public function index()
{
// create a list.
$products = JsonUtility::makeProductArray('products.json');
return view('products', ['products'=>$products]);
}
this is my route
Route::get('/product' , [ProductController::class, 'index'] );
how can i use this on my controller and what route should i set up to create a product
public static function addNewProduct(string $file, string $producttype, string $title, string $fname, string $sname, float $price, int $pages)
{
$string = file_get_contents($file);
$productsJson = json_decode($string, true);
$ids = [];
foreach ($productsJson as $product) {
$ids[] = $product['id'];
}
rsort($ids);
$newId = $ids[0] + 1;
$products = [];
foreach ($productsJson as $product) {
$products[] = $product;
}
$newProduct = [];
$newProduct['id'] = $newId;
$newProduct['type'] = $producttype;
$newProduct['title'] = $title;
$newProduct['firstname'] = $fname;
$newProduct['mainname'] = $sname;
$newProduct['price'] = $price;
if($producttype=='cd') $newProduct['playlength'] = $pages;
if($producttype=='book') $newProduct['numpages'] = $pages;
$products[] = $newProduct;
$json = json_encode($products);
if(file_put_contents($file, $json))
return true;
else
return false;
}
This is where i am trying to type to code into.
public function create()
{
//show a view to create a new resource
$products = JsonUtility::addNewProduct('products.json');
return view('products', ['products'=>$newProduct], );
}
your function addNewProduct() is expecting 7 parameters when called.
you are getting this error because you cannot provide those parameters that your function is looking for.
in your code above you are passing 'products.json' which is in a string format.
lets assume that it is a JSON data. it will still fail because you are only passing 1 parameter to a function that is expecting 7 parameters.
what you could probably do is change it to
public static function addNewProduct($data)
{
// code here
}
then you can pass your JSON data and then go through each of your json using a loop.

Undefined property: App\Cart::$totalPrice

Hello I am making a cart but when I click on add to cart link then it says:
Undefined property: App\Cart::$totalPrice
Error: https://ibb.co/ysB5CfG
model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Cart
{
private $contents;
private $totalQty;
private $contentsPrice;
public function __construct($oldCart){
if ($oldCart) {
$this->contents = $oldCart->contents;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}
public function addProduct($product, $qty){
$products = ['qty' => 0, 'price' => $product->price, 'product' => $product];
if ($this->contents) {
if (array_key_exists($product->slug, $this->contents)) {
$product = $this->contents[$product->slug];
}
}
$products['qty'] +=$qty;
$products['price'] +=$product->price * $product['qty'];
$this->contents[$product->slug] = $product;
$this->totalQty+=$qty;
$this->totalPrice += $product->price;
}
public function getContents()
{
return $this->contents;
}
public function getTotalQty()
{
return $this->totalQty;
}
public function getTotalPrice()
{
return $this->totalPrice;
}
}
controller:
public function cart()
{
if (!Session::has('cart')) {
return view('products.cart');
}
$cart = Session::has('cart');
return view('product.cart', compact('cart'));
}
public function addToCart(Product $product, Request $request, $qty= null)
{
if(empty(Auth::user()->email)){
$data['email'] = '';
}else{
$data['email'] = Auth::user()->email;
}
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$qty = $request->qty ? $request->qty : 1;
$cart = new Cart($oldCart);
$cart->addProduct($product, $qty);
Session::put('cart', $cart);
return redirect()->back()->with('flash_message_success', 'Product $product->title has been successfully added to Cart');
}
routes:
Route::get('cart', 'Admin\ProductController#cart')->name('product.cart');
// Add to cart
Route::get('/addToCart/{product}/{qty?}', 'Admin\ProductController#addToCart')->name('addToCart');
You should use get() methods in cart() function in controller file.
public function cart()
{
if (!Session::has('cart')) {
return view('products.cart');
}
$cart = Session::get('cart');
return view('product.cart', compact('cart'));
}

Too few arguments to function App\Http\Controllers\homepageController::edit_web_services(), 0 passed and exactly 1 expected

my function
public function post_sofware_technology(Request $request)
{
$titile = $request->input('category_title');
$excerpt = $request->input('Excerpt');
$post = new posts();
$post->post_title = $titile;
$post->post_excerpt = $excerpt;
$post->save();
$soft_id = $post->id;
$this->edit_web_services($soft_id);
}
Another Function
public function edit_web_services($soft_id)
{
$soft = $soft_id;
dd($soft);
}
I want to pass my $soft_id = $post->id; value from post_sofware_technology() method to edit_web_services($soft_id) within the same controller.
try with this
public function post_sofware_technology(Request $request)
{
$titile = $request->input('category_title');
$excerpt = $request->input('Excerpt');
$post = new posts();
$post->post_title = $titile;
$post->post_excerpt = $excerpt;
$post->save();
$soft_id = $post->id;
return $this->edit_web_services($soft_id);
}

Payment Shopping cart - Laravel different Objects

I try to add different objets to my shopping Cart view in laravel, but I get an exception when I try to add different objects to the view. I would like to know if someone knows a good practice to achieve this.
Here my Class to get item type number 1:
<?php
namespace App;
class CartCotisationStructure
{
public $items = null ;
public $totalQty = 0 ;
public $totalPrice = 0 ;
public function __construct($oldCart)
{
if ($oldCart){
$this->items = $oldCart->items;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}
public function add($item , $id){
$storedItem = ['qty' => 0 , 'montant' => $item->montant , 'item' => $item];
if($this->items){
if(array_key_exists($id , $this->items)){
$storedItem = $this->items[$id];
}
}
$storedItem['qty']++;
$storedItem['price'] = $item->montant * $storedItem['qty'];
$this->items[$id] = $storedItem;
$this->totalQty++;
$this->totalPrice += $item->montant;
}
}
here my item type number two :
<?php
namespace App;
class CartLicenceStructure
{
public $items = null ;
public $totalQty = 0 ;
public $totalPrice = 0 ;
public function __construct($oldCart)
{
if ($oldCart){
$this->items = $oldCart->items;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}
public function add($item , $id){
$storedItem = ['qty' => 0 , 'mt_cotisation' => $item->activite_licencie->mt_cotisation , 'item' => $item];
if($this->items){
if(array_key_exists($id , $this->items)){
$storedItem = $this->items[$id];
}
}
$storedItem['qty']++;
$storedItem['price'] = $item->activite_licencie->mt_cotisation * $storedItem['qty'];
$this->items[$id] = $storedItem;
$this->totalQty++;
$this->totalPrice += $item->activite_licencie->mt_cotisation;
}
}
here my controller for LicenceStructure :
public function getAddToCart(Request $request , $id){
$licencie = LicencieStructure::find($id);
$oldCart = Session::has('CartLicenceStructure') ? Session::get('CartLicenceStructure') : null ;
$cart = new CartLicenceStructure($oldCart);
$cart->add($licencie , $licencie->id);
$request->session()->put('CartLicenceStructure' , $cart);
return redirect()->route('home')->with('status', 'Le licencié à bien été ajouté au panier');;
}
public function getCart()
{
if(!Session::has('CartLicenceStructure')){
return view('shop.panier');
}
$oldCart = Session::get('CartLicenceStructure');
$cart = new CartLicenceStructure($oldCart);
return view('shop.panier' , ['licencies' => $cart->items , 'totalPrice' => $cart->totalPrice]);
}
here my controller for Cotisations
public function getAddToCartCotisation(Request $request , $id){
$cotisation = CotisationStructure::find($id);
$oldCart = Session::has('CartLicenceStructure') ? Session::get('CartCotisationStructure') : null ;
$cart = new CartCotisationStructure($oldCart);
$cart->add($cotisation , $cotisation->id);
$request->session()->put('CartCotisationStructure' , $cart);
return redirect()->route('home')->with('status', 'La cotisation à bien été ajouté au panier');;
}
public function getCartCotisation()
{
if(!Session::has('CartCotisationStructure')){
return view('shop.panier');
}
$oldCart = Session::get('CartCotisationStructure');
$cart = new CartCotisationStructure($oldCart);
return view('shop.panier' , ['cotisations' => $cart->items , 'totalPrice' => $cart->totalPrice]);
}
And here my view ( who make an exception when i want to add two different items , "undefined variable "licences" )
#if(Session::has('CartLicenceStructure'))
#foreach($licencies as $licencie)
// display the items
#endforeach
#elseif(Session::has('CartCotisationStructure')
#foreach($cotisations as $cotisation)
// display the items
#endforeach

Resources