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

调用->user()->id时报Trying to get property 'id' of non-object错误如何解决

错误根因

报错Trying to get property 'id' of non-object指向的Auth::guard('client')->user()->id调用,触发原因是Auth::guard('client')->user()返回了null,说明当前没有通过client guard认证的登录用户,此时调用不存在的对象属性就会抛出该异常,通常出现在用户登录状态过期、未登录就访问该逻辑,或是client guard配置错误的场景下。

修复方案

方案1:提前拦截未登录状态

如果该逻辑只允许已登录的客户端用户访问,可以在业务代码执行前先校验登录状态,未登录时直接按业务需求返回对应结果:

if (app_config('sender_id_verification') == '1') {
    // 提前校验client guard登录状态,未登录直接返回空数组
    if (!Auth::guard('client')->check()) {
        $sender_ids = [];
        // 可在此处补充未登录的业务逻辑,比如跳转登录页、抛出权限异常等
    } else {
        $all_sender_id = SenderIdManage::where('status', 'unblock')->get();
        $all_ids = [];
        // 提前提取当前登录用户id,避免循环内重复调用
        $current_client_id = Auth::guard('client')->user()->id;

        foreach ($all_sender_id as $sid) {
            $client_array = json_decode($sid->cl_id);

            if (isset($client_array) && is_array($client_array)) {
                if (in_array('0', $client_array) || in_array($current_client_id, $client_array)) {
                    array_push($all_ids, $sid->sender_id);
                }
            }
        }
        $sender_ids = array_unique($all_ids);
    }
}

方案2:兼容未登录场景不拦截

如果业务允许未登录用户访问该逻辑,不需要提前拦截,只需要在原有判断条件里加登录校验即可,修改elseif分支的判断条件:

// 原代码
elseif (isset($client_array) && is_array($client_array) && in_array(Auth::guard('client')->user()->id, $client_array))

// 修改后代码
elseif (isset($client_array) && is_array($client_array) && Auth::guard('client')->check() && in_array(Auth::guard('client')->user()->id, $client_array))

如果完成上述修改后仍然报错,可检查config/auth.php配置文件中client guard的配置是否正确,是否关联了正确的用户提供器。

内容的提问来源于stack exchange,提问作者madmann

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 06:27:04