如何使用数组将数据放入 laravel 会话?

Posted

技术标签:

【中文标题】如何使用数组将数据放入 laravel 会话?【英文标题】:how to put data to laravel session uing array of array? 【发布时间】:2019-04-24 18:44:34 【问题描述】:

我正在尝试制作购物车并有以下要求: 1.当用户点击添加到购物车产品时添加到会话中,如下所示:

    Array
    (
        [items] => Array
            (
                [0] => Array
                    (
                        [product_id] => 15
                        [addtocart_totalmrp] => 8953
                        [addtocart_totalsellingprice] => 7876
                        [addtocart_auid] => 7065bec17a101cf2,3025bec186520de3,6725bec18d7889a7
                    )

                [1] => Array
                    (
                        [product_id] => 39
                        [addtocart_totalmrp] => 12654
                        [addtocart_totalsellingprice] => 11876
                        [addtocart_auid] => 1675bed115132bc6,755bed11033fe7d
                    )

            ),
                [2] => Array////which is not coming after 2 it stops and start overwriting the 2nd position 
                    (
                        [product_id] => 39
                        [addtocart_totalmrp] => 12654
                        [addtocart_totalsellingprice] => 11876
                        [addtocart_auid] => 1675bed115132bc6,755bed11033fe7d
                    )

            )

    )

这是我的代码:

$cart1 = array("product_id" => $request->product_id,
                "addtocart_totalmrp" => $request->addtocart_totalmrp,
                "addtocart_totalsellingprice" => $request->addtocart_totalsellingprice,
                "addtocart_auid" => $request->addtocart_auid);


            if ($request->session()->has('cart')) 

                $products = Session::get('cart.items', array());  // get existed products or empty array

                $products["items"][] = $cart1;                      // add new product to list
                echo'<pre>';
                print_r($products);


                Session::push('cart.items', $products);      //putting that data to cart 

                print_r(count($products));
                dd($products);

             else 
                echo 'session haas no data';
                $products["items"][] = $cart1;                      // add new product to list
                print_r($products);
                Session::put('cart.items', $products); 

            

我的问题: 当我尝试添加第三个产品时,它会覆盖第二个不知道该怎么做。

我已经尝试过这段代码及其工作,但是我再次使用了项目键,这里有任何建议是数组结构:

array:1 [
  "items" => array:4 [
    "items" => array:1 [
      0 => array:4 [
        "product_id" => "39"
        "addtocart_totalmrp" => "12654"
        "addtocart_totalsellingprice" => "11876"
        "addtocart_auid" => "1675bed115132bc6,755bed11033fe7d"
      ]
    ]
    0 => array:4 [
      "product_id" => "28"
      "addtocart_totalmrp" => "17145"
      "addtocart_totalsellingprice" => "12165"
      "addtocart_auid" => "5205bed102b6d856,8255bed103e3ce14"
    ]
    1 => array:4 [
      "product_id" => "15"
      "addtocart_totalmrp" => "8953"
      "addtocart_totalsellingprice" => "7876"
      "addtocart_auid" => "7065bec17a101cf2,3025bec186520de3,6725bec18d7889a7"
    ]
    2 => array:4 [
      "product_id" => "15"
      "addtocart_totalmrp" => "8953"
      "addtocart_totalsellingprice" => "7876"
      "addtocart_auid" => "7065bec17a101cf2,3025bec186520de3,6725bec18d7889a7"
    ]
  ]
]

我的新代码

if ($request->session()->has('cart')) 

//                 $productsfromsession = Session::get('cart', array());  // get existed products or empty array
// dd($productsfromsession);
//                 $products["items"][] = $cart1;                      // add new product to list
//                 echo'<pre>';
//                 print_r($products);



                Session::push('cart.items',$cart1);      //putting that data to cart 
                $a=Session::get('cart', array());
                //print_r(count($products));
                dd($a);

             else 
                echo 'session haas no data <pre>';
                $products["items"][] = $cart1;                      // add new product to list
                print_r($products);
                Session::put('cart.items', $products); 

            

根据答案更新代码:

$cart1 = array("product_id" => $request->product_id,
                "addtocart_totalmrp" => $request->addtocart_totalmrp,
                "addtocart_totalsellingprice" => $request->addtocart_totalsellingprice,
                "addtocart_auid" => $request->addtocart_auid);



if ($request->session()->has('cart')) 




                Session::push('cart.items',$cart1);      //putting that data to cart 
                $a=Session::get('cart', array());
                //print_r(count($products));
                dd($a);

             else 
                echo 'session haas no data <pre>';
                $products = [ $cart1 ];  // create a new cart and add a product in it
                Session::put('cart.items', $products); 
                print_r($products);
            

代码完美运行,但替换问题又开始了,我的代码中缺少什么?

这就是我想要的我的代码,这是一个在回答中问的问题:

public function addtocart(Request $request) 


// if user logged in check login and add data directly to cart without session 
        if (Auth::check()) 
            $user = Auth::user();
            echo 'auth sucess';
            //   adding data to table directly       //
         else 

// adding data to cart with session 

            $cart1 = array("product_id" => $request->product_id,
                "addtocart_totalmrp" => $request->addtocart_totalmrp,
                "addtocart_totalsellingprice" => $request->addtocart_totalsellingprice,
                "addtocart_auid" => $request->addtocart_auid);
            print_r('am current cart data : <pre>');
            print_r($cart1);

// checking for session has cart or not 

            if (Session::has('cartdata')) 

                echo ' session cart has data ';
             else 

                echo 'session has no data add first data to session ';
            
        
    


我已经尝试了 JSON 结构的新概念,当我尝试将数据放入数组时,请帮助我哪里出错了,它会在第二个位置之后停止推送数组 这是我的代码:

// adding data to cart with session
            $cartdata = array("product_id" => $request->product_id,
                "addtocart_totalmrp" => $request->addtocart_totalmrp,
                "addtocart_totalsellingprice" => $request->addtocart_totalsellingprice,
                "addtocart_auid" => $request->addtocart_auid);
            // print_r('am current cart data : <pre>');
             //print_r($cartdata);


// checking for session has cart or not

            if (Session::has('cartdata')) 

              // dd(Session::get('cartdata'));

                 echo ' session cart has new data and it is :<pre> ';

                 //// fethcing old data from session
                $productsfromsession = Session::get('cartdata');  // get existed array value


            //   decoding old data to normal array 
                $data=json_decode($productsfromsession);


                //dd($data); 


                // pushing new data to old product array 

                 array_push($data->products,$cartdata);


                // saving new data and encoding it again 
                $newdata=json_encode($data);

                dd($newdata);               ///every time i add data to this array its stop after 2nd inserted 
                // removing old data from session 
                  $request->session()->forget('cartdata');


                // putting new data to session   
                 Session::put('cartdata',$newdata); 

                //  printing result 
                dd(Session::get('cartdata'));

            //// printng current cart data after pusing new data


              else 


                  echo 'session has no data adding  first data to session is <pre>';

                  //     // putting first item to array
                  $products[]=$cartdata;
                 $cartdata=array("total_price"=>10,"products"=>$products);
            $cartdata=json_encode($cartdata);
              Session::put('cartdata', $cartdata);

                 $data = Session::all();
               print_r($data);
            

【问题讨论】:

使用Session::put('cart.items',$products["items"]) 感谢您的回答@leena Patel 我会在一分钟内检查它 仍然无法为第三个项目工作,它仍然在替换相同的项目。有什么建议吗? 值相同可能就是这个原因。 【参考方案1】:

试试这个:

Session::push('cart.items', $cart1);

有关 Session 的更多信息,请查看以下内容:

https://laravel.com/docs/5.7/session#storing-data

【讨论】:

感谢 JOSH 的回复,我已经尝试推送,但问题仍然是更新我的新代码等待..【参考方案2】:

在您的新代码中,当会话中没有“购物车”时,我发现这是一件很奇怪的事情。

$products["items"][] = $cart1;  // add new product to 
print_r($products);
Session::put('cart.items', $products);

上面的代码将创建一个嵌套在“items”下的产品数组,它本身就是嵌套的。

[
   "cart" => [
      "items" => [
          "items" => [ $cart1 ]
      ]
   ]
]

Session::push 相当健壮。在将给定值附加到它之前,它已经预先检查了会话中给定键的值。当值不是数组时,它会初始化一个空并附加给定的值。

if-else 分支在使用 Session::push 时变得多余。

$cart = [/*...*/];
Session::push('cart.items', $cart);

【讨论】:

感谢您的回复 Oluwafemi sule 现在工作正常,但更换问题又开始了 哦,我明白了。我认为if-else 出了点问题,我无法说明。 Session::push 似乎已经在做 if-else 所做的事情,并使显式检查变得多余。

以上是关于如何使用数组将数据放入 laravel 会话?的主要内容,如果未能解决你的问题,请参考以下文章

如何取消设置 laravel 会话数组

Laravel - 将部分会话内容添加到数组中

当所有检索值在laravel中具有相同的会话键时,如何检查会话数组是不是具有唯一的ID

如何解决这个 Laravel 会话问题

如何在 laravel 中进行会话?

如何从 laravel 中的会话数组中删除项目