抱歉,我无法找到更好的标题。
我想展示"关注" 或"编辑个人资料"链接,取决于经过身份验证的用户是否正在观看自己的个人资料或其他用户的个人资料。
这是我的刀片代码:
@if(isLogedIn())
@if($authedUser->id !== $profile->user()->find(1)->id)
{{link_to_action('RelationshipsController@add', 'Follow', $profile->user()->find(1)->id, ['class' => 'button radius'])}}
@else
{{link_to_action('ProfilesController@edit', 'Edit Profile', $authedUser->id, ['class' => 'button radius'])}}
@endif
@endif
现在,如果我正在观看其他用户'配置文件一切正常(if
语句正常工作,我可以看到Follow
链接),但是如果我尝试查看自己的配置文件,laravel会抛出异常:Trying to get property of non-object
。这里的事情是$profile->user()->find(1)->id
抛出异常,因为当我将其硬编码为整数时,一切正常。
以下是导致异常的行:
<?php if($authedUser->id !== $profile->user()->find(1)->id): ?>
PS1:问题不是嵌套if
s。
PS2:在这种情况下,我的代码永远不会触及else
部分。
修改 这是ProfileController @ show:
public function show($userId)
{
try{
$profile = $this->profileRepo->byForeignKey('user_id',$userId)->firstOrFail();
}catch(ModelNotFoundException $e){
throw new ProfileNotFoundException('profile not found');
}
return View::make('profiles.show')->with('profile', $profile);
}
答案 0 :(得分:2)
来自评论:&#34;因为我需要用户的ID。 $profile->user()
返回BelongsTo对象,因此我使用find(1)
来获取User对象。&#34;
在这种情况下,您可以使用动态属性user
,而不是调用user()
。
@if($authedUser->id !== $profile->user->id)
与
相同@if($authedUser->id !== $profile->user()->get()->id)
但是你不能在这里使用find(1)
。它将尝试使用id = 1