0

I have two related tables like this:

publishers

| id | name     |
|----|----------|
| 1  | EA Games |
| 2  | Nintendo |

games

| id | publisher_id | title       |
|----|--------------|-------------|
| 1  | 1            | FIFA 2014   |
| 2  | 2            | Super Mario |
| 3  | 1            | The Sims    |

My index page is built like this:

public function index(){
    $games = Game::all();
    return View::make('/games/index', compact('games'));
}

And of course my Blade template is like this:

<table class="table table-striped">
    <thead>
        <tr>
            <th>Title</th>
            <th>Publisher</th>
            <th>Complete</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        @foreach($games as $game)
        <tr>
            <td>{{ $game->title }}</td>
            <td>{{ $game->publisher_id }}</td>
            <td>{{ $game->complete }}</td>
            <td>
                <a href="{{ action('GamesController@edit', $game->id) }}" class="btn btn-default">Edit</a>
                <a href="{{ action('GamesController@delete', $game->id )}}" class="btn btn-danger">Delete</a>
            </td>
        </tr>
        @endforeach
    </tbody>
</table>

In the Publishers' cells I'd like to display the publisher name (taken from the 'publishers' DB table), not the publishers' IDs

Please, how can I achieve this?

Thanks in advance

Ivan
  • 2,463
  • 6
  • 39
  • 51

1 Answers1

1

You need to setup your model relationship by adding this method to your Game model:

public function publisher()
{
    return $this->belongsTo('Publisher');
}

Then you can use $game->publisher->name in your view.

vmikki
  • 26
  • 2