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

ronon's avatar
Level 9

Show images in gallery and on user profile, without belongsToThrough relation

I have the following problem. I have three models User, Image and Gallery. The images table contains all images ever uploaded. For example avatar images, and so on.

I have the following relations:

class User extends Model {
    
    public function images(){
        return $this->hasMany(Image::class);
    }
}


class Image extends Model {
    
    public function user(){
        return $this->belongsTo(User::class);
    }
}


class Gallery extends Model {
    
    public function images(){
        return $this->hasMany(Image::class);
    }
}

Now I have a few problems:

  1. How should I assing the images to the Gallery? An Image belongs to only one Gallery.
  2. I need to display the images on the user profile WITHOUT the gallery. Just the plain images. It could be that the gallery gets deleted, but without the images, they need to be visible on the user profile at all. So a belongsToThrough relation won't work.

Should I do it with a polymorphic relation, or... I currently don't have a plan.

0 likes
0 replies

Please or to participate in this conversation.