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

时间:2018-07-07 03:15:37

标签: php laravel

每当我进入用户个人资料页面且用户没有关注者时,都会出现以下错误。我正在使用laravel follow

  

试图获取非对象的属性           $ user-> followers-> get();

当用户确实有关注者时,它会显示没有错误的关注者。

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');
    }

2 个答案:

答案 0 :(得分:1)

MyFollow模型

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');
    }
}

控制器更改

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);
}

查看

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

答案 1 :(得分:0)

因此,只需在返回值之前进行完整性检查即可。

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

根据关注者的构成方式,您可能需要$user->followers->count()