Hola
Hola

Reputation: 2233

Laravel : Removing Array item from Session

I was trying to remove array item from Session. I have shown the array element following way:

<?php $i=1; ?>

@foreach(Session::get('product') as $row)
    <tr>
        <td>
            <img src="{{asset('files/'.$row->thumbnil)}}" class="img-thumbnail" alt="" width="90px">
        </td>
        <td>{{$row->name}}</td>
        <td>
            <a href="{{asset('deleteEnquote/'.$row->id)}}">  
                <button class="btn btn-danger btn-sm"><i class="fa fa-remove"></i></button>
            </a>
        </td>
    </tr>
<?php $i++; ?>  
@endforeach

And this is how I was trying to remove the key element :

public function deleteEnquote($id)
{

    $remove = Product::where('id',$id)->first();

    if(Session::has('product')){
        foreach (Session::get('product') as $key => $value) {
            if($value === $remove){
                Session::pull('product.'.$key); // retrieving pen and removing
                break;
            }
        }
    }

    return redirect('enquote');
}

But the problem is I couldn't delete the appropriate element from the Array.Means element not deleted.How do I delete the specific element from Session Array?

Upvotes: 0

Views: 1723

Answers (2)

hizbul25
hizbul25

Reputation: 3849

If product is your session array then use following code:

if(Session::has('product')){
  foreach (Session::get('product') as $key => $value) {
    if($value === $remove){
      session()->forget('product.'.$key)
      break;
    }
  }
}

Upvotes: 0

Deepansh Sachdeva
Deepansh Sachdeva

Reputation: 1198

You need to do something like this:

  1. Get the array.
  2. Using unset function remove that key.
  3. Set the updated array again to session with same key.

    $product = Session::get('product'); //step 1
    unset($product[$key]);              //step 2
    Session::put('product', $product);  //step 3
    

Upvotes: 1

Related Questions