用户注销时如何避免空致命错误 | Laravel 5.4
How to avoid null fatal error when user its logged out | Laravel 5.4
我正在构建的应用程序有一个功能,登录用户可以拖放图片上传到服务器。
问题是,当用户未登录时,我希望在视图中隐藏上传部分。这是我的上传视图逻辑:
@if($user->owns($post))
<hr>
<h2>Add Your Photos</h2>
<form action="{{route('store_photo_path', [$post->slug, $post->location])}}" class="dropzone" id="addPhotosForm">
{{csrf_field()}}
</form>
@endif
如您所见,我编写了逻辑来查看用户是否已登录,但它给了我错误 Call to a member function owns() on null
注意:owns() 是在 User 模型上创建的方法。
public function owns($relation){
return $relation->user_id=$this->id;
}
注意 $relation var 它的 post object 在视图上可用,它被发送到函数以检查创建 post 的用户是否是与登录用户相同。
我正在尝试检查我们是否有任何登录用户,如果有,我正在使用 owns()
方法检查登录用户是否是 post 本身的所有者。但是当我没有用户登录时,我得到空错误?!
也许我的方法是错误的任何建议?!
P.s $user 它是一个全局 blade 视图变量,在我的 AppServiceProvider 上的 boot()
方法中初始化,就像这样;
public function boot()
{
//
Schema::defaultStringLength(191);
//return authenticated user to all views
\View::composer('*', function($view){
$view->with('user', \Auth::user());
});
owns
检查登录用户是否拥有 post。它不检查用户是否登录。
你可以这样做:
@if(Auth::check() && $user->owns($post))
<hr>
<h2>Add Your Photos</h2>
<form action="{{route('store_photo_path', [$post->slug, $post->location])}}" class="dropzone" id="addPhotosForm"> {{csrf_field()}} </form>
@endif
希望对你有帮助
已解决:检查用户是否存在并拥有post。
@if($user && $user->owns($post))
<hr>
<h2>Add Your Photos</h2>
<form action="{{route('store_photo_path', [$post->slug, $post->location])}}" class="dropzone" id="addPhotosForm">
{{csrf_field()}}
</form>
@endif
我正在构建的应用程序有一个功能,登录用户可以拖放图片上传到服务器。
问题是,当用户未登录时,我希望在视图中隐藏上传部分。这是我的上传视图逻辑:
@if($user->owns($post))
<hr>
<h2>Add Your Photos</h2>
<form action="{{route('store_photo_path', [$post->slug, $post->location])}}" class="dropzone" id="addPhotosForm">
{{csrf_field()}}
</form>
@endif
如您所见,我编写了逻辑来查看用户是否已登录,但它给了我错误 Call to a member function owns() on null
注意:owns() 是在 User 模型上创建的方法。
public function owns($relation){
return $relation->user_id=$this->id;
}
注意 $relation var 它的 post object 在视图上可用,它被发送到函数以检查创建 post 的用户是否是与登录用户相同。
我正在尝试检查我们是否有任何登录用户,如果有,我正在使用 owns()
方法检查登录用户是否是 post 本身的所有者。但是当我没有用户登录时,我得到空错误?!
也许我的方法是错误的任何建议?!
P.s $user 它是一个全局 blade 视图变量,在我的 AppServiceProvider 上的 boot()
方法中初始化,就像这样;
public function boot()
{
//
Schema::defaultStringLength(191);
//return authenticated user to all views
\View::composer('*', function($view){
$view->with('user', \Auth::user());
});
owns
检查登录用户是否拥有 post。它不检查用户是否登录。
你可以这样做:
@if(Auth::check() && $user->owns($post))
<hr>
<h2>Add Your Photos</h2>
<form action="{{route('store_photo_path', [$post->slug, $post->location])}}" class="dropzone" id="addPhotosForm"> {{csrf_field()}} </form>
@endif
希望对你有帮助
已解决:检查用户是否存在并拥有post。
@if($user && $user->owns($post))
<hr>
<h2>Add Your Photos</h2>
<form action="{{route('store_photo_path', [$post->slug, $post->location])}}" class="dropzone" id="addPhotosForm">
{{csrf_field()}}
</form>
@endif