当用户没有关注者时,尝试获取非对象错误的属性

I get the following error, whenever i go to a user profile page and the user doesn't have followers.I am using laravel follow

Trying to get property of non-object $user->followers->get();

When a user does have followers it shows the followers with no errors.

MyFollow.php

class MyFollow extends Model
{
    use SoftDeletes, CanFollow, CanBeFollowed;

    protected $fillable = [
        'user_id',
        'followable_id'
    ];

    public $timestamps = false;

    protected $table = 'followables';

    public function followers()
    {
        $user = User::find($this->user_id); 

        $user->followers->get();


    }



}

UserController.php

public function getProfile($user)
{  
        $user = User::with(['posts.likes' => function($query) {
                            $query->whereNull('deleted_at');
                        }])
                      ->where('name','=', $user)

                      ->with(['follow' => function($query) {

                            $query->with('followers');

                       }])->first();


        if(!$user){
            return redirect('404');
        }

        return view ('profile')->withUser($user);
}

Profile.blade.php

            @foreach($user->followers as $use)
                    @isset($use->name)
                    <ul>

                        <li>{{$use->name}}</li>
                     @endisset
                    </ul>



            @endforeach

User.php

  public function follow()
    {   
        return $this->hasMany('App\MyFollow');
    }

MyFollow Model

class MyFollow extends Model
{
    use SoftDeletes, CanFollow, CanBeFollowed;

    protected $fillable = [
        'user_id',
        'followable_id'
    ];

    public $timestamps = false;

    protected $table = 'followables';

    public function follower()
    {
        return $this->belongsTo('App\User', 'followable_id');
    }
}

change in controller

public function getProfile($user)
{  
        $user = User::with(['posts.likes' => function($query) {
                            $query->whereNull('deleted_at');
                        }, 'follow','follow.follower'])
                      ->where('name','=', $user)->first();


        if(!$user){
            return redirect('404');
        }

        return view ('profile')->with('user', $user);
}

View

@foreach($user->follow as $follow)
     <ul>
        @if($follow->follower)
           <li>{{$follow->follower->name}}</li>
        @endif
    </ul>
@endforeach

So, just do a sanity check before returning a value.

public function followers()
{
    $user = User::find($this->user_id); 
    if ($user->followers) 
    { 
        return $user->followers->get(); 
    } else {  
        return "No Followers"; 
    }
}

Depending on how followers is constructed, you may need $user->followers->count()