Laravel多认证环境下调用unreadNotification()报Null错误求助
解决Laravel多认证下Web模板获取Admin未读通知报错的问题
这个问题我之前帮朋友排查过类似的,核心原因其实是守卫上下文不匹配导致的admin()->user()返回了null——毕竟当前请求是用web守卫认证的普通用户,admin守卫并没有对应的登录用户,直接调用unreadNotifications()自然会报错。咱们分场景来解决:
场景1:你需要统计所有管理员的未读通知总数
这种情况不需要依赖登录状态,直接查询数据库即可,推荐两种高效写法:
写法1:通过Admin模型关联统计
// 可以放在控制器里传给视图,或者直接在blade里用@php块 $totalAdminUnread = \App\Models\Admin::withCount('unreadNotifications')->sum('unread_notifications_count');
写法2:直接查询通知表(性能更优)
$totalAdminUnread = \App\Models\Notification::where('notifiable_type', \App\Models\Admin::class) ->whereNull('read_at') ->count();
场景2:你需要获取特定管理员的未读通知(比如某个固定ID的管理员)
如果是要展示某个指定管理员的通知,先确保能拿到有效的Admin实例,再做统计,记得加存在性判断避免报错:
@php // 替换成你的目标管理员查询逻辑,比如根据ID、角色等 $targetAdmin = \App\Models\Admin::find(1); $adminUnreadCount = $targetAdmin ? $targetAdmin->unreadNotifications->count() : 0; @endphp <p>管理员未读通知:{{ $adminUnreadCount }}</p>
场景3:你确实需要当前登录管理员的通知(同一会话多守卫登录)
如果你的业务允许普通用户和管理员同时登录(需要自定义会话处理),那一定要先判断admin守卫是否有登录用户,再调用方法:
@if(Auth::guard('admin')->check()) {{ Auth::guard('admin')->user()->unreadNotifications->count() }} @else 0 @endif
额外检查:确保Admin模型的通知关联正确
最后确认你的Admin模型已经正确引入Notifiable trait并配置了通知关联:
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Notifications\Notifiable; class Admin extends Model { use Notifiable; // 如果你自定义了通知表,需要重写notifications方法 public function notifications() { return $this->morphMany(\App\Models\Notification::class, 'notifiable'); } // 未读通知的关联(Laravel默认已实现,可省略) public function unreadNotifications() { return $this->notifications()->whereNull('read_at'); } }
内容的提问来源于stack exchange,提问作者PICKAB00
相关产品推荐
相关产品推荐

