简体   繁体   中英

How to avoid null fatal error when user its logged out | Laravel 5.4

The app that I am building has a feature where the logged in user has the chance to drag n'drop pictures to upload to the server.

The thing is that when the user its not logged in I want the upload section to be hidden on the view. Here is my logic on upload view:

 @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 

As u can see I wrote the logic to see if the user its logged in, but its giving me the error Call to a member function owns() on null

Note: owns() its a method created on the User model.

public function owns($relation){

    return $relation->user_id=$this->id;

 }

Note $relation var its the post object that its available on the view and it is being sent to the function to check if the user who has created the post is same as logged in user.

I am trying to check if we have any logged in user and if so with owns() method i am checking to see if the logged in user is the owner of the post itself. But when I have no users logged in I get the null error ?!

Maybe my approach is wrong any suggestion ?!

Ps $user its a global blade view variable initialized on my boot() method on AppServiceProvider like so;

public function boot()
{
    //
     Schema::defaultStringLength(191);

    //return authenticated user to all views
    \View::composer('*', function($view){
    $view->with('user', \Auth::user());
});

The owns checks if logged in user owns the post. It doesn't check if the user is logged in. You could do this:

@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 

Hope it helps

Got it solved: Check if the user exists and has a 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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM