Laravel Eloquent - list of parent from a collection

1.1k views Asked by At

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');
    }
}
2

There are 2 answers

0
Guilherme Miranda On BEST ANSWER

Made it work with

$store->medias()->whereHas('likes', function($q) use($user) {
        return $q->where('user_id', '=', $user->id);
    });
2
Marcin Nabiałek On

This is because you get media separate for each like. You should use:

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

foreach ($likes as $like) {
   $media = $like->media;
   // now you can do something with your media
}

EDIT

If you want to get only media, you should add to your User model the following relationship:

public function medias()
{
    return $this->hasManyThrough('App\Media','App\Like');
}

Now to get your media, you should do :

$medias = User::find(1)->medias()->where('store_id', '=', 1)->get();