문제

I am following a tutorial on Laravel 4 but I am stuck at a specific point. I want to return a view showing the user with his photos. For this I have the following method in my controller:

    public function show($id)
{
    $user = User::whereId($id)->with('photo')->first();

    return View::make('authenticated.users.show', compact('user'));
}

If I return $user the json I am seeing in the browser seems to be perfectly correct.

However, if I try to display that in the show.blade.php view I am getting this error:

Undefined property: Illuminate\Database\Eloquent\Collection::$id

The code I am using in my view is the following:

 <li>{{ $user->photo->id }}</li>

Its exactly as shown in the tutorial but it does not work out.

I would very much appreciate some help.

Thanks.

도움이 되었습니까?

해결책

It's most like that you are using the hasMany relationship in your User model. When using the hasMany relationship, it will return a Collection object, rather than your model itself. Take a look at the API for the Collection object and you'll find many helpful methods.

What you should probably do is something like this.

foreach ($user->photo->all() as $photo)
{
    echo $photo;
}

Or, if your user only has one photo, then change your relationship in the User model to hasOne. Then you can use it as you are now.

echo $user->photo;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top