Yasir
Yasir

Reputation: 1070

Laravel 5 database relationship - get data on another table

I have 3 table. I need to jump movie_name from reservations. I have allready getting data from showtime but I can not go forward there.

reservations->id - I am getting showtime_id clumn (its ok.) 
$reservation->showtime['movie_id'] - I am getting movie_id (its ok.)
But I need movie name.

Database

- reservations
id
showtime_id
....

- showtimes
id
movie_id
..

- movies
id
movie_name
..

My View

@foreach ($reservations as $reservation)
    <tr>
    <td>{{$reservation->id}}</td>
    <td>{{$reservation->fullname}}</td>
    <td>{{$reservation->showtime['movie_time']}}</td>
    <td>Movie Name</td>
    </tr>
@endforeach

I have listing reservations like this. My Controller

public function Reservations()
{
    $reservations = \App\Reservation::paginate(20);
    return view('admin.reservations', ['reservations' => $reservations]);
}

My Modal

class Reservation extends Model
{
    public function showtime(){
        return $this->belongsTo('App\Showtime');
    }
}

Upvotes: 0

Views: 60

Answers (1)

Wreigh
Wreigh

Reputation: 3287

Create a relationship in Showtime model for retrieving the movie which is related to it.

// Showtime.php
public function movie()
{
    return $this->belongsTo(Movie::class);
}

And now you can access it.

$reservation->showtime->movie->movie_name;

Upvotes: 4

Related Questions