php - 当用户没有关注者时尝试获取非对象错误的属性
问题描述
每当我转到用户个人资料页面并且用户没有关注者时,我都会收到以下错误。我正在使用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');
}
解决方案
我的关注模型
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
推荐阅读
- arrays - 如何使用循环获取用户输入的字符串
- python - 如何在 tkinter 中打开 SVG 文件?
- c++ - 点没有颜色,即使有着色器
- sql-server - SQL Server :Resolve Blocking with concurrent writes and reads
- dosbox - 如何在 Retroflag GPI 上配置 DOSBox 游戏中的键?
- node.js - 使用 mocha 和 chai 进行 Nodejs api 休息测试。待发帖
- python - seaborn中的Swarmplot,每个点都有不同的颜色
- ios - 使用临时配置文件重新签署使用 export_method“app-store”导出的 IPA
- sql - SQL Error: An expression of non-boolean type specified in a context where a condition is expected, near 'AND'
- wordpress - Raspberry Pi local wordpress unreachable