简体   繁体   English

Laravel:从会话中删除数组项

[英]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? 但是问题是我无法从Array.Means元素中删除适当的元素,如何从会话数组中删除特定的元素?

You need to do something like this: 您需要执行以下操作:

  1. Get the array. 获取数组。
  2. Using unset function remove that key. 使用unset功能删除该键。
  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 

If product is your session array then use following code: 如果product是您的会话数组,则使用以下代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM