テーブルを結合し画面上に表示させたい
bookテーブルのuser_idとuserテーブルのidを紐付けuserテーブルのnameを画面表示したい。
Userモデル
public function book() { return $this->belongsTo(Book::class); }
Bookモデル
public function user() { return $this->hasMany(User::class); }
TopController
<?php namespace App\Http\Controllers; use App\User; use App\Book; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class TopController extends Controller { public function index() { $user = Auth::user(); $books = Book::all(); $param = ['books' => $books, 'user' => $user]; return view('top.index', $param); } }
index画面
@extends('layouts.home') @section('content') <h2>Book List</h2> @if (Session::has('msg')) <p>{{ session('msg') }}</p> @endif @if (Auth::check()) <p>{{$user->name}}</p> @endif <table class="table table-bordered text-center"> <tr> <th>タイトル</th> <th>著者</th> <th>投稿者</th> <th>評価</th> </tr> @foreach ($books as $book) <tr> <td><a href="/book/{{ $book->id }}">{{ $book->name }}</a></td> <td>{{ $book->person }}</td> <td><a href="/user/{{ $user->id }}">{{ $book->user_id }}</a></td> <td>{{ $book->score }}</td> </tr> @endforeach </table> @endsection
現状
$book->user_idで画面上では登録したユーザーのIDが表示されているが、こちらをuserテーブルのnameを表示できるようにしたい
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。