Jagdish Sharma
Jagdish Sharma

Reputation: 309

how to put data to laravel session uing array of array?

I am trying to make a cart and have the following requirements : 1.when user click adds to cart product added to the session like this:

    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
                    )

            )

    )

here is my code:

$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); 

            }

my problem: when I try to add a third product it is overwriting the 2nd one don't know how to do it.

I have tried this code and its working but there is item key I used once coming again any suggestion for this here is the array structure:

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"
    ]
  ]
]

my new code

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); 

            }

New UPdate of code as per answer:

$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);
            }

code work perfectly but the issue of replacing started again something missing in my code?

here is what i want my code is this a sper asked in answers:

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 ';
            }
        }
    }

}

I have tried a new concept of JSON structure can u plz help me where am wrong whenever I try to put data on to array it goes and stop pushing array after 2nd position here is my Code:

// 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);
            }

Upvotes: -1

Views: 101

Answers (2)

Oluwafemi Sule
Oluwafemi Sule

Reputation: 38982

In your new code, I find this a curious thing to do when there is no "cart" in the session.

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

This above code will create an array of products nested under "items" which itself is nested.

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

Session::push is fairly robust. It already pre-checks the value for the given key in the session before appending the given value to it. When the value isn't an array, it initializes an empty one and appends the given value.

The if-else branch becomes redundant when using Session::push.

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

Upvotes: 1

Josh Young
Josh Young

Reputation: 1366

Try this:

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

for more info on Session have a look at this:

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

Upvotes: 1

Related Questions