Search code examples
phplaraveleloquentlaravel-5laravel-collection

Laravel Eloquent - list of parent from a collection


I can get the list of Likes that User 1 did on a Media from Store 1

$medias = User::find(1)->likes()->with('media')->whereHas('media', function($q) {
    $q->where('store_id', '=', 1);
})->get();

But i need to retrieve the list of medias, so i tried

$medias = User::find(1)->likes()->with('media')->whereHas('media', function($q) {
    $q->where('store_id', '=', 1);
})->get()->media;

But then i get

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

class User extends Model
{
    public function likes()
    {
        return $this->hasMany('App\Like');
    }
}

class Media extends Model
{
    public function store()
    {
        return $this->belongsTo('App\Store');
    }

    public function likes()
    {
        return $this->hasMany('App\Like');
    }
}

class Like extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function media()
    {
        return $this->belongsTo('App\Media');
    }
}

Solution

  • Made it work with

    $store->medias()->whereHas('likes', function($q) use($user) {
            return $q->where('user_id', '=', $user->id);
        });