I am trying to get first image from table related to id but unfortunately getting all images instead of first image

Viewed 24

I am trying to get first image from table but unfortunately i am getting all images related to id ,i need only first one image from table please help me how can resolve that ? thanks

enter image description here

Room table

id | name | description

31 | co working space | fsdfdsf

Room detail

id | room_id | image

1 | 31 | php8AB0.tmp.PNG

2 | 31 | php8AB0.tmp.PNG

**Controller **

 public function index()
    {
        $data=[
            'rooms' => Room::with('roomDetail')->orderBy('created_at','DESC')->paginate(3),
            // 'roomDetail'=> RoomDetail::get(),
        ];

        return view('cms.rooms',$data);

    }


                <div class="row">
                  <div class="col-md-12">
                    @if(count($rooms) > 0)
                        @foreach ($rooms as  $value)
                        @foreach ($value->roomDetail as $value2)
                            <div class="card mb-4">
                                <div class="d-flex">
                                <img height="145px" src="{{Config('wfh.file').$value2->image}}" alt="">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-center">
                                    <div class="left">
                                        <h4 class="fw-bold">{{$value->name}}</h4>
                                        <p class="mb-2">{{$value->description}}</p>
                                        <span class="badge bg-light-outline p-2 me-1"> <i class='bx bx-                            user'></i> {{$value->capacity}}</span>
                                    </div>
                                    <button class="btn bg-primary-light px-3 me-2 py-2"><i class='bx   bxs-wrench'></i></button>
                                    </div>
                                </div>
                                </div>
                            </div>
                        @endforeach
                        @endforeach

                     @endif
                     {!! $rooms->links('pagination::bootstrap-4') !!}
                  </div>
                </div>
1 Answers

If you only want the first roomDetail instead of all, dont iterate over them with foreach.

Instead use $value->roomDetail->first() and then take the attributes you want from it.

For your Image for example use:

<img height="145px" src="{{ Config('wfh.file') . $value->roomDetail->first()->image }}" alt="">
Related