Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Penaf's avatar
Level 1

Lookup table between two models

Having 3 SQL tables

images
- id

galleries
- id

images_galleries
-images_id
-galleries_id

How can I relate in the Galeries model the hasMany images?

I have this but doesn't feel like being the correct thing to do:

class Gallery extends Model
{

    protected $table = 'galleries';

    protected $guarded = ['id'];

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


}
0 likes
12 replies
staudenmeir's avatar
Level 24

This is a BelongsToMany relationship (documentation):

public function images ()
{
    return $this->belongsToMany('App\Image', 'images_galleries', 'galleries_id', 'images_id');
}
1 like
newbie360's avatar

images_galleries is pivot table

so you need use belongsToMany

1 like
Cronix's avatar

The joining table also needs to be the singular form of both tables it's joining, and in alphabetical order, so it should be image_gallery

1 like
Penaf's avatar
Level 1

Thanks @staudenmeir @newbie360 and @Cronix for the prompt replies! I'm still very fresh to laravel and dind't understand the mechanics of belongsToMany

About your reply @Cronix ... you are talking about the table names or the ids?

Is this ok?

images
- id

galleries
- id

image_gallery
- id_image
- id_gallery
1 like
Tray2's avatar

I would just have two table for that instead of three.

galleries
- id
- description

images
-id
-image
-gallery_id

Unless of course the image can belong to multiple galleries.

1 like
newbie360's avatar

if image not belongsToMany galleries

i will

galleries
- id
- description

images (PK = gallery_id+image)
-gallery_id
-image
-image_order
1 like
Penaf's avatar
Level 1

@Cronix Thanks mate!

@Tray2 & @newbie360 yup ... images will belong to multiple galleries as well as they might be used on other parts of the application... so having a belongsToMany on the galleries part will leave the db open to more flexibility for the future.

Thanks everybody for the swift and detailed and suggestive answers... as usual ... this community is awesome! :)

1 like
Cronix's avatar

@penaf You're welcome! If you have it working now, please mark your thread as solved.

1 like
Penaf's avatar
Level 1

@Cronix : by the way, you most surelly can help me out with this one (don't know if I should ask a new question instead of asking here...)

On my GalleryController.php I have this:

    public function data()
    {
        $resultados = Galery::all();

        foreach ($resultados as $resultado){
            $resultado->multimedia_count = Galery::images()->withCount('image_id');
        }

    return DataTables::of($resultados)->make(true);
    }

I'm messing up big time am I not?

1 like

Please or to participate in this conversation.