dongrouli2667 2017-09-09 16:50
浏览 97

Laravel:从Session中删除Array项

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?

  • 写回答

2条回答 默认 最新

  • dongluo3331 2017-09-09 16:54
    关注

    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
      
    评论

报告相同问题?