首页 > 解决方案 > 如何从 Laravel 会话数组中获取行 ID 并删除该特定行?

问题描述

我想从存储的会话数组中删除一行。我可以通过像下面的代码行那样静态发送行号来成功删除它。但在这里我想通过传递数组行 ID 或行号来动态地做到这一点。我想用数组行号或 ID 的 'item_id' 替换 '0'。我如何从数组中获取该 ID?

$request->session()->pull('quoteSession.'.$id.'.vibrantScope.0');

这是使用上面的代码删除第一条记录后我的数组控制台日志。

quoteSession:
  125:
    vibrantScope:
       1: "Array line 2"
       2: "Array line 3"
       3: "Array line 4"
       4: "Array line 5"

这是我的刀片代码


@foreach(Session::get('quoteSession.'.$lead->id.'.vibrantScope') as $item)
  <tr>
      <td scope="row">{{$loop->iteration}}</td>
      <td class="p-1 min-w-100" width="">
          {{$item}}
      </td>
      <td class="text-center">
          <a href="javascript:void(0);" onclick="removeScopeSession('{{$lead->id}}', '{{$item_id}}')" id="removeScope" title="Remove Scope" class="text-danger h6"><span class="fa fa-minus-circle"></span></a>                                        
      </td>
  </tr>
@endforeach

这是我的 onClick Ajax 调用函数来调用删除控制器

function removeScopeSession(lead_id, item_id){
    $.ajax({
        type: "post",
        url:"/scope/ajaxRemoveVibrantScopeSession",
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },        
        data:{
            lead_id : lead_id,
            item_id : item_id,
        },
        dataType: 'json', 

        success: function(response){
            console.log(response);
            $("#tblVibrantScope").load(" #tblVibrantScope > *");
            toastr.success(' ', 'Scope Removed', {timeOut: 3000, positionClass: 'toast-bottom-right'});
            },
        error: function(error){
            console.log(error);
            toastr.error(' ', 'Scope not Removed', {timeOut: 3000, positionClass: 'toast-bottom-right'});
        }
    });
}

这是我的控制器功能。在这里,我想用数组行号或 ID 的 'item_id' 替换 '0'。

    public function ajaxRemoveVibrantScopeSession(Request $request)
    {
        $id = $request->lead_id;
        $item_id = $request->item_id;
        $delete_data = 'quoteSession.'.$id.'.vibrantScope.0';
        $request->session()->forget($delete_data);
        return $request->session()->all();
    }  

标签: arrayssession-variablessession-managementdelete-recordlaravel-session

解决方案


终于自己从堆栈中找到了答案。

使用 @foreach(Session::get('quoteSession.'.$lead->id.'.vibrantScope') as $key => $value) 在 for 循环中分隔数组键和值,然后您可以访问它们带有 $key 和 $value

$key 将返回数组的键,即 [1]

$value 将返回数组的值,即 [Array line 2]

看下面的代码

@foreach(Session::get('quoteSession.'.$lead->id.'.vibrantScope') as $key => $value)
  <tr>
    <td scope="row">{{$loop->iteration}}</td>
    <td class="p-1 min-w-100" width="">
        {{$value}}
    </td>
    <td class="text-center">
       <a href="javascript:void(0);" onclick="removeScopeSession('{{$lead->id}}', '{{$key}}')" id="removeScope" title="Remove Scope" class="text-danger h6"><span class="fa fa-minus-circle"></span></a>                                        
    </td>
  </tr>
@endforeach

推荐阅读