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

Time:04-06

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 >
                  <div >
                    @if(count($rooms) > 0)
                        @foreach ($rooms as  $value)
                        @foreach ($value->roomDetail as $value2)
                            <div >
                                <div >
                                <img height="145px" src="{{Config('wfh.file').$value2->image}}" alt="">
                                <div >
                                    <div >
                                    <div >
                                        <h4 >{{$value->name}}</h4>
                                        <p >{{$value->description}}</p>
                                        <span > <i class='bx bx-                            user'></i> {{$value->capacity}}</span>
                                    </div>
                                    <button ><i class='bx   bxs-wrench'></i></button>
                                    </div>
                                </div>
                                </div>
                            </div>
                        @endforeach
                        @endforeach

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

CodePudding user response:

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