Search code examples
laraveloptimizationrelationship

laravel how to get image information from relationship and optimize it


Product model
id (column)
productname (column)

ProductGallery model
galleryid (column)
productid (column)

Galleries model
id (column)
imagename (column)

hello i want retrive data like this, my model is in the top

"id" => 1
productname => "product 1"
galleries => {
   0 => {
         id => 1,
         imagename => 'image 1'
        }
   1 => {
         id => 2,
         imagename => 'image 2'
        }
}

how can i achive this using relationship and optimize?


Solution

  • Set relationship on your models.

    Products Model

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

    And on your controller you can get data like this

    Procuct::with('galleries')->get();