Search code examples
mysqlsqllaravellaravel-query-builderlaravel-9

Laravel select row and its child rows


As a Laravel beginner,

I have a gallery table as follows

id     |     gallery_name    | published
-------+---------------------+------------
1      |    name             |  1
-------+---------------------+------------
2      |    name 2           |  1
-------+---------------------+------------

And another table ( gallery_images) to store images associated with each gallery

id   |   gal_id    |   image_name
-----+-------------+--------------
1    |   1         | image_01
-----+-------------+--------------
2    |   1         | image_02
-----+-------------+--------------
3    |   2         | image_03
-----+-------------+--------------

In my controller fetching the gallery by the following code

$data['galleries']= Gallery::where('published','=',1)->orderBy('id','DESC')->paginate(5);

Showing the gallery in view like this.

@foreach($data['galleries'] as $gal)
    <h3>{{$gal['gallery_name']}}</h3>
    <p>{!! html_entity_decode($gal['gallery_text']) !!}</p>
    // Show images associated with each gallery
@endforeach

Now I need to show images associated with each gallery from gallery_images.

What is the best practice to call a function from view ? or are there any other ways?


Solution

  • You can define a one-to-many relationship, add this function in gallery model:

    public function galleryImages()
    {
        return $this->hasMany(gallery_images::class, 'gal_id');
    }
    

    Now change your view file:

    @foreach($data['galleries'] as $gal)
        <h3>{{$gal['gallery_name']}}</h3>
        <p>{!! html_entity_decode($gal['gallery_text']) !!}</p>
        @foreach($gal->gallerImages as $image)
            // Show image associated with $gal
        @endforeach
    @endforeach