Laravel blade: if .. her expression behaves unexpectedly

Sorry, I couldn't find a better title for this question.

I want to display a "follow" or "Edit Profile" link , depending on whether the authenticated user is viewing their profile or another user profile.

Here is my blade code:

@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

      

Now if I go through the profiles of other users everything is fine (the operator if

works and I see the link Follow

). However, if I try to look at my own profile, Laravel throws: Trying to get property of non-object

. The thing is, it $profile->user()->find(1)->id

throws this exception because when I hardcoded that integer everything worked correctly.

Here is the line that throws the exception:

<?php if($authedUser->id !== $profile->user()->find(1)->id): ?>

      

PS1: Problem is not nested if

s.

PS2: In this situation, my code never touches a part else

.

EDIT: Here is 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);
}

      

+3


source to share


1 answer


From comments: "because I need a user id. $profile->user()

Returns a BelongsTo object, so I used find(1)

to get a User object."

In this case, you can use a dynamic property user

instead of calling user()

.

@if($authedUser->id !== $profile->user->id)

      



Same as

@if($authedUser->id !== $profile->user()->get()->id)

      

But you cannot use find(1)

here. It will try to find the object withid = 1

+2


source







All Articles