2016-08-22 5 views
1

가 나는 동안이 같은 열망로드 갤러리이점점 오류 열망로드

$user = User::where('username', $username)->first(); 
     $favorites = Favorite::with('gallery')->where('user_id', $user->id)->get(); 
     dd($favorites->gallery); 

이 오류 메시지가 점점 :

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

즐겨 찾기 클래스는 다음과 같습니다

class Favorite extends Model 
{ 
    protected $table = 'favorites'; 
    public function user(){ 
     return $this->belongsTo(User::class, 'user_id'); 
    } 
    public function gallery(){ 
     return $this->belongsTo(Gallery::class, 'gallery_id'); 
    } 
} 

을 그러나 내가 이것을하면

$user = User::where('username', $username)->first(); 
     $favorites = Favorite::with('gallery')->where('user_id', $user->id)->get(); 
     dd($favorites); 

(10)는 다음 나는이 image

답변

1

$favorites이 모음입니다 얻을 당신은 컬렉션의 속성을 얻을 수 없습니다.

당신은 콜렉션에서 첫 번째 개체를 얻을 수 first()를 사용해야합니다 :

$favorites = Favorite::with('gallery')->where('user_id', $user->id)->first(); 

또는 수집을 반복하고 모든 개체를 얻을 :

foreach ($favorites as $favorite) { 
    echo $favorite->gallery; 
}