Faizi
Faizi

Reputation: 109

Get Foreign key data in laravel

I have two tables room and room_images. In room_images table, we have multiple images of one room. Now i want to show those images in room edit blade template.


    rooms table:   | room_image table:
    id (PK)        | id
    title          | room_id (FK)
    desc           | room_image

Room Edit Controller

`public function edit($id)
 { 
    $room = Room::find($id);
    if(auth()->user()->id !== $room->user_id){
        return redirect('/rooms')->withStatus(__('Unauthorized Page'));
    }
    return view('rooms.edit')->with('room' , $room);
 }`

Room Modal: Room.php

`public function user()
 {
    return $this->belongsTo('App\User');
 }
 public function tbl_roomimages()
 {
    return $this->hasMany('App\RoomImage');
 }`

Room Image Modal: RoomImage.php

`public function tbl_rooms()
 {
   return $this->belongsTo('App\Room','room_id');
 }`

Here is the database column pictures: Room images tbl

Room tbl

Upvotes: 0

Views: 516

Answers (2)

DevBodin
DevBodin

Reputation: 211

Alright, I've got a couple things for ya. Let's see how I do.

First, the issue with your Models:

You have the relationship functions named with a leading "tbL_" which in Laravel is going to affect the foreign key they look for. Instead, you need to use snake case. So, for instance, your Room-RoomImages relationship needs to be this:

 public function room_images()
 {
    return $this->hasMany('App\RoomImage');
 }`

[Quick note: this might actually just be a standard naming convention. It's good practice either way, but I might be wrong on the foreign key connection. Feel free to call me out on it.]

Then, the Controller

Then, just as a matter of efficiency, I recommend "eager-loading" your room images. So, in the controller, change over to this:

$room = Room::with("room_images")->find($id);

Then, finally, in your view

Assuming "room_image" is actually a "src" value, do this:

@foreach($room->room_images as $img)

   <img src="{{ $img->room_image }}" />

@endforeach

And, assuming that is indeed just the src path, I'd really recommend changing the field name to reflect that to avoid confunsion.

Now, a couple tips:

One: "Modal" -> "Model." (A Modal is a pop-up window.)

Two: if you use compact(), you can save yourself a lot of redundancy in the event you have lots of variables to pass to the view.

return view('rooms.edit')->with(compact('room', 'room_images', 'otherthing'));

Upvotes: 1

party-ring
party-ring

Reputation: 1871

The following should return the instance of the relationship from your model.

$roomImages = $room->tbl_roomimages()->get();

You will be able to access the column data from tbl_roomimages like

foreach($roomImages as $roomImage)
{
     $roomImage->room_image;
}

Upvotes: 1

Related Questions