2

I am new to laravel and I am struggling to retrieve data using the query Builder.

Consider the following migration on the Hotel table:

$table->id();   
$table->timestamps();          
$table->foreignIdFor(User::class);     
$table->foreignIdFor(Room::class);    

Now consider that I have in my HotelController:

$hotel = Auth::user()->hotels which retrieves this on dd:

[{"id":1, "user_id":51,"room_id":11, "booking_id":7}

[{"id":2, "user_id":51,"room_id":16, "booking_id":21}

[{"id":3, "user_id":51,"room_id":18, "booking_id":44}

[{"id":4, "user_id":51,"room_id":45, "booking_id":33}

I now want to retrieve the data from each of the room_id and booking_id from each of the Auth users which in this case is user 51. Can anyone help me with how can I achieve this?

Thank you in advance

1 Answers1

1

Assuming you defined the relationships (belongsTo, hasOne, hasMany, etc) in the models for Hotel, Room and Booking, you can just iterate through the list of hotels getting each hotel into a $hotel local variable, and asking for their related models information like this:

foreach ($hotels as $hotel) {
    $hotel->room // gets you the related room
    $hotel->booking // gets you the related booking
}
  • 1
    This was the simple solution I needed! Yes, I forgot to mention I had the relationships sorted. Thank you so much for your time – thecodewanderer Sep 24 '22 at 14:42