You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中展示双用户记录表格时出现foreach参数为空的错误求助

Laravel中展示双用户记录表格时出现foreach参数为空的错误求助

嘿,我帮你排查出问题啦!你遇到的foreach() argument must be of type array|object, null given错误,根源出在控制器里的方法调用和数据返回上,咱们一步步来解决:

问题原因分析

  1. 你的user_record()方法里,虽然查询出了当前用户的记录$show_leave,但没有把这个查询结果返回出去,所以当你在show_user_record()里调用$this->user_record()时,得到的是null,自然在视图里foreach循环的时候就报错了。
  2. 另外,你在show_user_record()里的变量命名有点混乱,$show_leave和$user_record的对应关系没理清楚,也容易导致后续出错。

修正后的控制器代码

咱们把控制器的两个方法调整一下,确保数据能正确传递:

public function user_record()
{
    $user_id = Auth::user()->id;
    // 把查询结果return出去,这样调用这个方法才能拿到数据
    return DB::table('user_record')->where('user_id','=',$user_id)->get();
}

public function show_user_record(Request $request)
{
    $user_id = Auth::user()->id;
    // 获取当前用户作为主管的下属记录
    $show_user_record = DB::table('user_record')->where('supervisor','=',$user_id )->get();
    // 获取当前用户自己的记录,这里接收user_record()返回的数据
    $current_user_records = $this->user_record();
    
    // 把两个变量传递到视图,注意变量名要和视图里对应上
    return view('/user_records', compact('show_user_record','current_user_records'));
}

修正后的视图代码

接下来把视图里的第二个foreach循环的变量改成我们新定义的$current_user_records,避免变量名混淆:

<!-- 第一个表格:当前用户作为主管的下属记录 -->
<table>
    <tr>
        <th>#</th>
        <th>Full Name</th>
        <th>Status</th>
        <th>Remarks</th>
    </tr>
    @foreach($show_user_record as $data)
    <tr>
        <td>{{$data->id}}</td>
        <td>{{$data->full_name}}</td>
        <td>{{$data->status}}</td>
        <td>{{$data->remarks}}</td>
    </tr>
    @endforeach
</table>

<!-- 第二个表格:当前用户自己的记录 -->
<table>
    <tr>
        <th>#</th>
        <th>Full Name</th>
        <th>Status</th>
        <th>Remarks</th>
    </tr>
    <!-- 这里把$user_record改成$current_user_records -->
    @foreach($current_user_records as $user_data)
    <tr>
        <td>{{$user_data->id}}</td>
        <td>{{$user_data->full_name}}</td>
        <td>{{$user_data->status}}</td>
        <td>{{$user_data->remarks}}</td>
    </tr>
    @endforeach
</table>

额外优化建议

为了代码更清晰,你可以把两个查询都放在show_user_record()方法里,不用单独拆成user_record(),这样代码更集中,可读性更强,也不容易出现方法返回值的问题:

public function show_user_record(Request $request)
{
    $user_id = Auth::user()->id;
    // 当前用户自己的记录
    $current_user_records = DB::table('user_record')->where('user_id','=',$user_id)->get();
    // 当前用户作为主管的下属记录
    $show_user_record = DB::table('user_record')->where('supervisor','=',$user_id )->get();
    
    return view('/user_records', compact('show_user_record','current_user_records'));
}

备注:内容来源于stack exchange,提问作者Untamable Beast

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.20 11:25:31