選択したidのページにてid個別の情報を出そうと思っています。
ふたつのモデルにはいっているデータを呼び出したいのですがうまくできません。。
hasMany/belongsToでモデルにて結合しています。
web
1Route::get('book/select/{id}', 'BookController@select');
BookController
1<?php 2 3namespace App\Http\Controllers; 4 5use App\Book; 6use App\Author; 7use Illuminate\Http\Request; 8 9class BookController extends Controller { 10 11{省略} 12 13 public function select(Request $request, $id) { 14 15 $author = \App\Author::find($id); 16 $name = $author->name; 17 $books = $author->books()->orderBy('created_at', 'DESC'); 18 19 return view('book.select')->with(array('author' => $author, 'name' => $name, 'books' => $books)); 20 } 21 22}
Author
1<?php 2 3namespace App; 4 5use Illuminate\Database\Eloquent\Model; 6 7class Author extends Model { 8 9 public $timestamps = false; 10 protected $fillable = [ 11 'name' 12 ]; 13 14 public function books() { 15 return $this->hasMany('App\Book'); 16 } 17 18} 19 20
Book(model)
1<?php 2 3namespace App; 4 5use Illuminate\Database\Eloquent\Model; 6 7class Book extends Model { 8 9 protected $fillable = [ 10 'title', 11 'author_name', 12 'company' 13 ]; 14 15 public function author() { 16 return $this->belongsTo('App\Author'); 17 } 18 19} 20
回答3件
あなたの回答
tips
プレビュー