niko craft
niko craft

Reputation: 2977

get all images that belong to a specific gallery

I want to get all images that belong to a specific gallery. These images have to be selected from Image class.

this is relationship, inside Image class:

public function galleries()
{
    return $this->belongsToMany(Gallery::class, 'gallery_image');
}

and inside Gallery:

public function images()
{
    return $this->belongsToMany(Image::class, 'gallery_image', 'gallery_id', 'image_id')->withPivot('order');
}

I have tried this:

$images = Image::with(array(
    'galleries' => function ($query) use($search)
    {
        $query->where('slug', $search);
    }->paginate()

but it still returns all images back even when I send it specific gallery.

Can anyone help me with this query?

It must be done with Image:: and not Gallery:: I must select images through image class and not Gallery class because of a specific way I am doing this. So I need help with above query and not a suggestion to go with Gallery::some_query_here

Upvotes: 0

Views: 86

Answers (2)

Rwd
Rwd

Reputation: 35170

You should be able to use whereHas:

$images = Image::with('galleries')
    ->whereHas('galleries', function ($query) use ($search) {
        $query->where('slug', $search);
    })
    ->paginate();

Hope this helps!

Upvotes: 1

thefallen
thefallen

Reputation: 9749

Why don't you try to get the gallery first and then get its images:

$gallery = Gallery::with('images')->whereSlug($slug)->first();
$images = $gallery->images;

Upvotes: 0

Related Questions