I have a laravel app that allows users to add reviews to a book.
My Routes are:
Route::get('/books/{book}/addreview', 'ReviewController@create');
Route::post('books/{book}/review', 'ReviewController@store');
My Review controller looks like:
public function create(Book $book) {
return view('/reviews/create');
}
public function store(Book $book){
$this->validate(request(),[
'title' => 'required',
'body' => 'required'
]);
Review::create([
'title'=>request('title'),
'body'=>request('body'),
'user_id'=>auth()->id(),
'book_id'=>$book->id
]);
// return redirect('/books');
}
However, I get 'Undefined variable: book' - So I'm not finding the current Book ID. How could I find the current Book ID and pass it to the view?
In Review Controller:
public function create(Book $book) {
return view('reviews.create', compact('book'));
}
In View:
{{ $book->id }}
You have to send data to view.
public function create(Book $book) {
return view('reviews.create', ['book' => $book]);
}
You're not passing anything to the view, you need to explicitly pass data to it so that it can be used:
return view('reviews.create', ['book' => $book]);
Then in your view, to access the book's ID you can use $book->id
:
Book ID is {{ $book->id }}.
// here I add some custom name to this route which will help to generate
// a corresponding URL in the view by passing this name
// route('routename')
Route::get('/books/{book}/addreview', 'ReviewController@create')->name('review.create');
Route::post('/books/{book}/review', 'ReviewController@store')->name('review.store');
In your controller which render the review.create
view you must pass the $book
that correspond to current model binding in your route like this
public function create(Book $book){
return View::make('reviews.create', ['book' => $book]);
}
and in the corresponding view when you create your form you must specify the action
attribute like this
<form action={{ route('review.store', $book)}} method="post">
{{ csrf_field}}
You should add public function store(Request $book)
instead public function store(Book $book)
As you didn't share your Book request file.