首页 > 解决方案 > 当用户没有关注者时尝试获取非对象错误的属性

问题描述

每当我转到用户个人资料页面并且用户没有关注者时,我都会收到以下错误。我正在使用laravel 跟随

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

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

我的关注.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();


    }



}

用户控制器.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);
}

配置文件.blade.php

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

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



            @endforeach

用户.php

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

标签: phplaravel

解决方案


我的关注模型

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

推荐阅读