Multiple collections in an array (session variable) — Property does not exist - arrays

I'am trying to fetch a session variable if the user is a guest. The variable is called "cart" and is set like this:
$product = new Collection((object) [
'product_id' => $request->pId,
'amount' => $request->amount,
'variations' => $variations
]);
Session::push('cart', $product);
Then I later fetch it:
if(Auth::check()){
$cartProducts = ShoppingCartItem::where('user_id', '=', Auth::user()->id)->get();
}else{
$cartProducts = Session::get('cart');
}
foreach($cartProducts as $product){
dd($product);
$totalAmount += $product->amount;
$totalPrice += (PriceHelper::getProductPrice($product->product->id, $product->amount));
}
The problem here is that dd($product) still outputs an array (the session variable array I assume) which means that for example $product->amount does not exist.
This is the output from dd($product):

You can either access the values using get():
foreach ($cartProducts as $product) {
$totalAmount += $product->get('amount');
$totalPrice += PriceHelper::getProductPrice($product->get('product_id'), $product->get('amount'));
}
or as an array:
foreach ($cartProducts as $product) {
$totalAmount += $product['amount'];
$totalPrice += PriceHelper::getProductPrice($product['product_id'], $product['amount']);
}
or you could use sum() on the collection instead of using foreach:
$cartProducts = collect(Session::get('cart'));
$totalAmount = $cartProducts->sum('amount');
$totalPrice = $cartProducts->sum(function ($product) {
return PriceHelper::getProductPrice($product['product_id'], $product['amount']);
});
Edit
For a quick fix if you need $product to be an object you could do something like:
$cartProducts = collect(Session::get('cart'))->map(function ($item) {
return (object)$item->toArray();
});
Hope this helps!

Related

laravel array sort by

data comes in fine. what i want to do is to sort the sizes sort by key 'size_piece' from smallest to largest. can you help me
Controller code;
foreach ($cco as $order_item){
foreach ($order_item->orderPiece as $piece_item){
$order_piece += $piece_item->piece;
$cut_order['cutting_piece'][$order_item->collectionColor->color_name]['size_piece'][$piece_item->CollectionColorSizeBarcode->size] = $piece_item->piece;
$cut_order['cutting_piece'][$order_item->collectionColor->color_name]['total_piece'] += $piece_item->piece;
}
$cut_order['order'][$order_item->id] = $order_item;
$cut_order['order'][$order_item->id]['total_piece'] = $order_piece;
$order_piece = 0;
}
return dd($cut_order);
Screen output like this;
If it there is no way to sort them before insertion.
The solution is to map your array:
use Illuminate\Support\Arr;
$mapped = Arr::map($cut_order['cutting_piece'], function ($value, $key) {
return Arr::set($value, 'size_piece', Arr::sort(Arr::get($value, 'size_piece', []));
});
$cut_order['cutting_piece'] = $mapped;
Documentation : Laravel Helper Array Map

foreach by quantity in laravel

I develop a ticketing system which user have to choose the quantity of ticket category. I want to save the record to database by the total of quantity. But it seems to be failed. I end up only save the record by category id. Here is the result when I try to return it.
and this is my code in controller.
public function ticket_checkout(Request $request)
{
$ctg_id = $request->cat_id;
$price = $request->price;
$name = $request->name;
$qty = $request->qty;
// return count($qty);
$data = [];
$i = 0;
foreach($qty as $item){
if($qty[$i] != 0){
$data[] = [
"ctg_id" => $ctg_id[$i],
"price" => $price[$i],
"qty" => $item,
];
}
$i++;
}
return $data;
Ticket_checkout::insert($data);
// return $qty;
return view('ticket.index', compact('data','qty'));
}
I wonder if I missing something here? I tried to do looping 'for' by quantity inside the 'foreach' but it seems not working too.

Symfony - saving array to database

I wrote a function where I get array of marks that i need to post to my database..
My function stores it in a filed row like:
And I need to pull just one per column individually like:
Here is my api call..
public function generate(Map $seatMap)
{
$layout = $seatMap->getSeatLayout();
$seats = [];
$layoutArray = json_decode($layout, true);
$columns = range('A', 'Z');
foreach($layoutArray as $index => $result)
{
$columnLetter = $columns[$index];
$letters = str_split($result);
$letterIndex = 1;
foreach($letters as $letterIndex => $letter) {
switch($letter) {
case 'e':
$seats[] = $columnLetter . $letterIndex;
$letterIndex++;
}
}
}
foreach($seats as $seat => $result) {
$result = new Seat();
$result->setName(json_encode($seats));
$this->em->persist($result);
$this->em->flush();
}
}
Any suggestions?
I think that problem is in the part where I need to store it to database..
If I understand you correctly, your issue is here:
foreach($seats as $seat => $result) {
$result = new Seat();
$result->setName(json_encode($seats));
$this->em->persist($result);
$this->em->flush();
}
}
You're indeed creating new Seat instance for every seat, but in this line:
$result->setName(json_encode($seats));
you still assign all (encoded) seats to every instance of Seat. What you want is to assign only the seat from current loop iteration, which is represented by $result variable.
So try with:
$result->setName($result);
You do not need json_encode here too.
If your array is like you say it it then try this
foreach($seats as $seat) {
$result = new Seat();
$result->setName($seat);
$this->em->persist($result);
$this->em->flush();
}

Persist array store in session symfony

It's been several days since I've been blocking to persist items from an order into session to database.
I stock articles in session in an array and I do not know how to persist the array. I try to convert the array into an object, I can not. This is my service:
public function addArticle($id)
{
$sessionCart = $this->session;
$article = $this->doctrine->getRepository('AppBundle:Article')->find($id);
$cart = $sessionCart->get('cart');
$cart[] = $article;
$sessionCart->set('cart', $cart);
// use later for delivery
$sessionCart->get('commande');
return $sessionCart;
}
public function panier()
{
$articles = $this->session->get('cart');
return $articles;
}
public function delivery(Request $request)
{
$commande = new Commande();
$articles = $this->session->get('cart');
$form = $this->form->create(CommandeType::class, $commande);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid())
{
$data = $form->getData();
$this->session->set('commande', $data);
$response = new RedirectResponse('payment');
$response->send();
}
return [$form, $articles];
}
public function payment(Request $request)
{
$articles = $this->session->get('cart');
$commande = $this->session->get('commande');
if ($request->isMethod('POST')) {
$em = $this->doctrine;
$em->persist($articles);
$em->persist($commande);
$em->flush();
}
return[$articles, $commande];
}
Error : "EntityManager#persist() expects parameter 1 to be an entity object, array given."
The order is persisted but not the items.
Thanks
I can't understand these two lines
$cart = $sessionCart->get('cart');
$cart[] = $article;
$sessionCart->set('cart', $cart);
$cart is an array and should be an entity isn't it ?
The persist is waiting for an entity,
maybe you can persist in a foreach loop:
foreach($articles as $article){
$em->persist($article);
}
or use a doctrineCollection instead of an array

How to delete Model Condition?

I wrote a function which is supposed to return an array of clubs for userId. I don't know why by when I add where(Model_ClubUsers::$USERS_ID,$userId) to dsql() it doesn't set the condition and I have to use addCondition(), but I need it only in this function. Is there a way to delete the condition before function returns?
function getUserClubs($userId){
$columns = array('id',self::$NAME,self::$LOGO_NAME,self::$DESC);
$this->addRelatedEntity('club_users', 'club_users', Model_ClubUsers::$CLUBS_ID, 'inner', 'related');
$this->addField(Model_ClubUsers::$USERS_ID)->relEntity('club_users');
$aAliasedColumns = $this->getAliasedColumns($columns, $this->entity_code);
$this->addCondition(Model_ClubUsers::$USERS_ID,$userId);
$rows = $this->dsql()->field($aAliasedColumns)->do_getAll();
$aResult = array() ;
foreach($rows as $key => $value){
foreach($value as $vKey => $vVal){
if($columns[$vKey]=='id'){
$aRow['key'] = $vVal;
}else if($columns[$vKey]==self::$LOGO_NAME){
$aRow[$columns[$vKey]] = self::$CLUBS_LOGO_PATH.$vVal;
}
else {
$aRow[$columns[$vKey]] = $vVal;
}
}
$aResult[] = $aRow;
}
return $aResult;
}
Please upgrade to 4.2 where the problem is no longer present:
$x=clone $this;
$x->addCondition();
also your syntax can be probably improved with the new 4.2 features.

Resources