david001's avatar

How to delete item from session

Hi, how can i delete data from session. it do not want delete all data by clicking single delete button. I have delete button for each data, so want to delete one by one. my current code is as follows:


public function deleteProduct(Request $request){
        $id = $request->productId;// this id i want to delete which i get from view
        $products = $request->session()->get('product');
    
        foreach ($products as $key => $value)
        {
            if ($value['id'] == $id) 
            {                
                unset($products [$key]);            
            }
        }
        //put back in session array without deleted item
        $request->session()->push('product',$products);
        //then you can redirect or whatever you need
        return redirect()->back();


    }

My data in session is in below format


[
{
id: 2,
name: "Marlene Reichert",
description: "Debitis asperiores sed sit assumenda unde quo natus. Consequatur est labore tenetur quae. Eius distinctio ea omnis aspernatur porro earum quae.",
category_id: 3,
price: 76,
image: "http://loremflickr.com/400/300?random=71",
created_at: "2019-07-16 10:12:27",
updated_at: "2019-07-16 10:12:27",
qty: 1
},
{
id: 6,
name: "Kaylin Emard",
description: "Et aperiam omnis nam iure id non fugiat. Excepturi voluptatem ipsam magnam. Esse asperiores ducimus enim et.",
category_id: 8,
price: 14,
image: "http://loremflickr.com/400/300?random=17",
created_at: "2019-07-16 10:12:27",
updated_at: "2019-07-16 10:12:27",
qty: 1
},
{
id: 5,
name: "Prof. Iliana Mohr",
description: "Autem sequi esse laudantium ut ut explicabo enim. Corporis cupiditate dolorum et ratione sequi architecto. Vitae enim ex hic nihil.",
category_id: 2,
price: 207,
image: "http://loremflickr.com/400/300?random=99",
created_at: "2019-07-16 10:12:27",
updated_at: "2019-07-16 10:12:27",
qty: 1
}
]

In my network tab, i got following error when i clicked the delete button

{message: "Invalid argument supplied for foreach()", exception: "ErrorException",…}
exception: "ErrorException"
file: "/Applications/XAMPP/xamppfiles/htdocs/fresh/app/Http/Controllers/ProductController.php"
line: 33
message: "Invalid argument supplied for foreach()"
trace: [{file: "/Applications/XAMPP/xamppfiles/htdocs/fresh/app/Http/Controllers/ProductController.php",…},…]
0: {file: "/Applications/XAMPP/xamppfiles/htdocs/fresh/app/Http/Controllers/ProductController.php",…}
1: {function: "deleteProduct", class: "App\Http\Controllers\ProductController", type: "->"}
2: {,…}
0 likes
22 replies
aurawindsurfing's avatar

Hey @david001

You are not getting anything from the session, you are not using the $productId anywhere.

$id = $request->productId;
$products = $request->session()->get('product');

This gives you probably an empty array as there is not key in session called product but probably products.

Try to do:

$id = $request->productId;
$products = $request->session()->get('product');
dd($products);

and see if you get anything in first place. That is why foreach throws an error as it gets nothing to loop.

So probably if you simply change your code to :

$id = $request->productId;
$products = $request->session()->get('products');

Then it should work.

david001's avatar

@aurawindsurfing doing this

$id = $request->productId;
$products = $request->session()->get('product');
dd($products);

In my network tab i got this


array:1 [
  0 => {#216
    +"id": 1
    +"name": "Keyshawn McDermott Sr."
    +"description": "Error aut quia id dolorem est aut doloribus nesciunt. Quod nihil tenetur ea id voluptas molestias id. Debitis amet dolor est fugiat sed autem."
    +"category_id": 1
    +"price": 59
    +"image": "http://loremflickr.com/400/300?random=36"
    +"created_at": "2019-07-16 10:12:27"
    +"updated_at": "2019-07-16 10:12:27"
    +"qty": 1
  }
]
aurawindsurfing's avatar

Sorry I did not notice the $id part.

Ok so maybe your data in session is not an array but a collection. In that case:

 foreach ($products as $product)
        {
            if ($product->id == $id) 
            {                
                $products->forget($product);            
            }
        }
david001's avatar

@aurawindsurfing , Thanks i got error this time on network tab

message: "Call to a member function forget() on array"

aurawindsurfing's avatar

Ok then you are probably getting nested array try:

$allProducts = $request->session()->get('product');
        
        foreach ($allProducts as $product){
            foreach ($product as $key => $value)
            {
                if ($value['id'] == $id)
                {
                    unset($allProducts [$key]);
                }
            }
        }
david001's avatar

now its gives another error message: "Illegal string offset 'id'"

AddWebContribution's avatar

Please use forget() for remove item from session like:

$request->session()->forget('abc.xyz.124');

// or use global helper
session()->forget('abc.xyz.124');

Please review this link

david001's avatar

@saurabhd ,Thanks, based on my session data above mentioned , how should it be? i tried number of above ways, didn't worked.

aurawindsurfing's avatar
$allProducts = $request->session()->get('product');
        
        foreach ($allProducts as $product){
            foreach ($product as $key => $value)
            {
                if ($key['id'] == $id)
                {
                    unset($allProducts[$id]);
                }
            }
        }
david001's avatar

@aurawindsurfing , i got same error again

{message: "Illegal string offset 'id'", exception: "ErrorException",…}```
Snapey's avatar
$products = collect($request->session()->get('product'));

$products = $products->reject(function($item)  use($id) {
        return $item['id'] == $id;
});

// save products back to session
david001's avatar

@snapey got this error {message: "Cannot use object of type stdClass as array",

Yevhenii's avatar

$products = collect($request->session()->get('product'));

$products = $products->reject(function($item) use($id) { return $item->id == $id; });

Snapey's avatar

Switch to object format

$products = collect($request->session()->get('product'));

$products = $products->reject(function($item)  use($id) {
        return $item->id == $id;
});

but if this does not work, you are going to have to var_dump the data so that we can see what we are dealing with

david001's avatar

@snapey

when i clicked delete button this is the error i can see in network tab

message: "Property [id] does not exist on this collection instance."

This are two methods


store in session
    public function StoreInCart(Request $request) {
        //dd(($request->product));
         $request->session()->push('product',json_decode($request->product));
         return session('product');
        
    }
    public function listProduct(Request $request){
//return from sessoion
        $product = $request->session()->get('product');
        return $product;
       
    }

on dd() , data in network tab


 $products = collect($request->session()->get('product'));
      dd($products);

Collection {#235
  #items: array:3 [
    0 => {#222
      +"id": 6
      +"name": "Kaylin Emard"
      +"description": "Et aperiam omnis nam iure id non fugiat. Excepturi voluptatem ipsam magnam. Esse asperiores ducimus enim et."
      +"category_id": 8
      +"price": 14
      +"image": "http://loremflickr.com/400/300?random=17"
      +"created_at": "2019-07-16 10:12:27"
      +"updated_at": "2019-07-16 10:12:27"
      +"qty": 1
    }
    1 => Collection {#223
      #items: []
    }
    2 => {#224
      +"id": 2
      +"name": "Marlene Reichert"
      +"description": "Debitis asperiores sed sit assumenda unde quo natus. Consequatur est labore tenetur quae. Eius distinctio ea omnis aspernatur porro earum quae."
      +"category_id": 3
      +"price": 76
      +"image": "http://loremflickr.com/400/300?random=71"
      +"created_at": "2019-07-16 10:12:27"
      +"updated_at": "2019-07-16 10:12:27"
      +"qty": 1
    }
  ]
}

This is the data return by second method in browser


[
{
id: 6,
name: "Kaylin Emard",
description: "Et aperiam omnis nam iure id non fugiat. Excepturi voluptatem ipsam magnam. Esse asperiores ducimus enim et.",
category_id: 8,
price: 14,
image: "http://loremflickr.com/400/300?random=17",
created_at: "2019-07-16 10:12:27",
updated_at: "2019-07-16 10:12:27",
qty: 1
},
[ ],
{
id: 2,
name: "Marlene Reichert",
description: "Debitis asperiores sed sit assumenda unde quo natus. Consequatur est labore tenetur quae. Eius distinctio ea omnis aspernatur porro earum quae.",
category_id: 3,
price: 76,
image: "http://loremflickr.com/400/300?random=71",
created_at: "2019-07-16 10:12:27",
updated_at: "2019-07-16 10:12:27",
qty: 1
}
]
Snapey's avatar

ok, so the error is because ONE of the products in session is empty, so when iterating over the collection with reject, it bails when it hits that item.

Either find out why you have an empty product in your session or use null coalesce operator to ignore the error

$products = collect($request->session()->get('product'));

$products = $products->reject(function($item)  use($id) {
        return $item['id'] ?? $id == $id;
});

the above will also reject empty entries as well as the one specified by $id

david001's avatar

i got this error : {message: "Cannot use object of type stdClass as array",}

so i is changed it to

        $id = $request->productId;
        
      $products = collect($request->session()->get('product'));

      $products = $products->reject(function($item)  use($id) {
        return $item->id?? $id == $id;//here
});

Now i didn't got any error, but still that item is in session, it is not removed from session even i clicked delete button for that item from my view page. do i need to update session?

Snapey's avatar

Yes, you have to write products back to the session.

session is a cupboard. You get the products out of the cupboard, change it and put it back.

$request->session()->put('product', $products);

make sure you don't use dd() after saving to the session since session is only stored at the end of the request cycle, and if you dd or crash before then, then the session state is not updated.

If you want to be able to inspect session data at any time, install Laravel Debugbar

david001's avatar

data is not removed from session


  $id = $request->productId;
        
    $products = collect($request->session()->get('product'));

$products = $products->reject(function($item)  use($id) {
        return $item->id ?? $id == $id;
});
 session()->put('product',$products);
jlrdw's avatar

I would suggest go to the documentation and deal with session exactly like Taylor shows, no other way whatsoever until you figure this out.

I've never seen this much trouble with session.

1 like

Please or to participate in this conversation.