非会员可以访问帖子页面,因此我试图使其变得可访问,但是出现以下错误:
Call to a member function postusers() on a non-object
如果我在验证时键入URL,则不会显示此错误。
用户模型中的postusers()方法:
public function postusers()
{
return $this->hasMany('App\Postusr');
}
postusers()的刀片用法:
@if( Auth::user()->postusers()->where('post_id', $post->id)->where('follow', 1)->exists())
如果我没有通过身份验证,我只是想访问此页面。
答案 0 :(得分:1)
问题是Auth::user()
方法返回被授权的用户;如果没有,则返回null。因此发生错误是因为您在null上调用postusers()
。
要解决此问题,您应该首先测试用户是否已通过身份验证,然后尝试调用该方法:
@auth
@if(...)
@endauth
@if(Auth::user() && ...)
答案 1 :(得分:1)
您可以通过刀片指令@auth
完成此操作@auth
@if( Auth::user()->postusers()->where('post_id', $post->id)->where('follow', 1)->exists())
@endauth
答案 2 :(得分:0)
在尝试调用可能不存在的对象之前,您需要检查是否有经过身份验证的用户:
@if (Auth::check())
... user is authenticated
@endif
@if (Auth::user())
... user is authenticated
@endif
Laravel 5.2 Docs - Authentication - Retrieving the Authenticated User