I'm learning Laravel 5. I'm trying to build a simple form to edit an existing record from the database, and I'm confused about how to use withInput() and old() in this case.
For example, consider the following routes and controllers:
<?php
// routes.php
use App\Book;
Route::get( '/book', [ 'as' => 'book.edit', function() {
$book = Book::find(1);
return view( 'book', [
'title' => $book->title
] );
} ] );
Route::post( '/book', [ 'as' => 'book.update', function() {
$validator = Validator::make( Request::all(), [
// This validator will (almost) always fail. This is deliberate, to
// illustrate the problem I'm describing.
'title' => 'in:zzzzz|required'
] );
if ( $validator->fails() ) {
return redirect( route('book.edit') )
->withInput()
->withErrors( $validator );
}
// TODO: save book
} ] );
Here's the corresponding template:
<!-- book.blade.php -->
<form action="" method="post">
<label>Book Title:</label>
<input type="text" name="title" value="">
@if ($errors->has('title'))
<strong></strong>
@endif
<button type="submit">Save</button>
</form>
Now, consider the following user flow:
-
The user requests GET /book (we'll call this page load #1). The
book.editcontroller loads the book's title (which happens to be "50 Shades of Grey") from the database, and passes that string off to the view. The user sees the form with the value "50 Shades of Grey" prepopulated in the field. So far, so good. -
The user modifies that title – say, to "A Tale of Two Cities" – and submits the form.
-
The
book.updateroute processes this request, and finds it invalid. It redirects the user back to thebook.editroute (we'll call this page load #2). -
book.editre-renders the same view, once again setting the value oftitleto "50 Shades of Grey" (which is incorrect).
This is the part I'm trying to solve: how can I display the title from the database on page load #1, but redisplay the user's input on page load #2?
Now, I understand why this code behaves this way. I just don't understand how I'm supposed to be doing it.
Possible solutions (and why I don't like them):
-
In my template, I could use
value=""instead ofvalue="". This will solve the problem on page load #2 – but it means that thetitlefield will be blank on page load #1. -
I could add some logic to the view – something like: This just feels hackish and wrong – it doesn't seem like the sort of thing that should be in the view.
-
I could add some logic to the
book.editrequest – something like'title' => $wasRedirected ? Request::get('title') : $book->title. This also feels hackish and wrong.
I'm probably just misunderstanding something, or missing something obvious. How is this aspect of edit forms usually handled in Laravel 5? There's gotta be a standard pattern, right?
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/254j1Sp
via IFTTT
Aucun commentaire:
Enregistrer un commentaire