php - Remove element from session array in laravel 5 -



php - Remove element from session array in laravel 5 -

i newbie in laravel 5 , trying create ecommerce web application learning on own.

i have next array of products:

array:2 [▼ 0 => array:4 [▼ "productid" => 3 "quantity" => 2 "productname" => "testing product 3" "productrate" => 275.0 ] 1 => array:4 [▼ "productid" => 2 "quantity" => 2 "productname" => "testing product 2" "productrate" => 180.0 ] ]

now when user clicks on x link in view of cart template, delete product session, removes total array of session cart on next page reload.

here's controller deleting product:

public function destroy($id) { if ( \session::has( 'cart' ) && is_array( \session::get('cart') ) ) { $cart = \session::get('cart'); ($i=0; $i < count($cart); $i++) { foreach ($cart[$i] $key => $value) { if ( $key === 'product' && $value == $id ) { unset( $cart[$i] ); } } } homecoming redirect('/cart')->with('cart', $cart); } }

i tried this:

unset( $cart[$i][$key] )

but gave me undefined index error.

kindly guide me have made error , solution it.

update 1:

here's index function:

public function index() { $cart = \session::get('cart'); homecoming view('cart.index')->with('cart', $cart); }

update 2: per discussion, here's destroy function:

public function destroy($id) { if ( \session::has( 'cart' ) && is_array( \session::get('cart') ) ) { $cart = \session::get('cart'); foreach ($cart $index => $product) { if ($product['productid'] == $id) { unset($cart[$index]); } } session(['cart' => $cart]); homecoming redirect('/cart'); } }

i suggest utilize foreach instead of for loop through array. because might error if array key not start 0 or there skip array key 0,1,3.

foreach ($cart $index => $product) { if ($product['productid'] == $id) { unset($cart[$index]); } } session(['cart' => $cart]);

i update code update $cart value (after removed product) session.

update not need with function after redirect function

return redirect('/cart')->with('cart', $cart);

to

return redirect('/cart');

php arrays session laravel laravel-5

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -