Laravel首页报错:Call to a member function manages() on null
解决Laravel中
Call to a member function manages() on null错误 问题原因
未登录用户访问首页时,auth()->user()会返回null,此时直接调用manages()方法就会触发该错误,错误位置在resources/views/layouts/navigation.blade.php第8行,对应代码为@if (auth()->user()->manages())。
解决办法
方法一:先校验用户登录状态
修改导航文件中的判断逻辑,先确认用户已登录,再调用方法:
@if (auth()->check() && auth()->user()->manages())
auth()->check()会验证当前是否有已登录用户,只有用户存在时才会执行后续的manages()校验。
方法二:使用可选链式调用(Laravel 8及以上版本支持)
利用PHP的可选链式操作符?->,当auth()->user()为null时,表达式直接返回null,不会触发错误:
@if (auth()->user()?->manages())
附用户提供的首页代码
<!-- resources/views/page.blade.php --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Front Page</title> </head> <body> <!-- Include the navigation menu --> @include('layouts.navigation') <!-- Your front page content goes here --> <h1>Welcome to the front page</h1> <p>This is the content of your front page.</p> </body> </html>
内容的提问来源于stack exchange,提问作者Mario
相关产品推荐
相关产品推荐

