I'm posting this because it was somewhat difficult to put together using the Laravel documentation. It is *there* in the docs, but it is split between different subjects. So here it is, all put together for your enjoyment:
I generally use redirects either when input fails validation or when the data has been saved and I'm ready to move to the next input page or a "finished" page. In the case of redirecting with input, we're talking about a validation failure (or some other error). The related redirect command is pretty straightforward:
return redirect()->back()->withInput();
The part I had trouble deciphering was how to retrieve that information into my blade view or controller. Note that the input is "flashed" to a session, which means it does not persist between page loads (it is deleted after the page loads). Fortunately, it turns out to be very simple to retrieve an input:
I generally use redirects either when input fails validation or when the data has been saved and I'm ready to move to the next input page or a "finished" page. In the case of redirecting with input, we're talking about a validation failure (or some other error). The related redirect command is pretty straightforward:
return redirect()->back()->withInput();
The part I had trouble deciphering was how to retrieve that information into my blade view or controller. Note that the input is "flashed" to a session, which means it does not persist between page loads (it is deleted after the page loads). Fortunately, it turns out to be very simple to retrieve an input:
// Controller: $first_name = old('first_name'); | |
// Blade: | |
{{ old('first_name') }} |
One gotcha is that the regular Blade "or" statement does NOT work ("or" in Blade brackets performs something like empty($var) ? $other_var : $var ). Instead of outputting the or statement, it outputs a boolean value:
// Outputs "1": | |
{{ old('first_name') or 'default value' }} |
Thankfully, the old() expression doesn't cause an error if the session variable isn't set, so you can use it without an "or" statement. Or if you need the "or", you can just write your own shorthand expression.
// Outputs $_SESSION['first_name'] or 'Sally': | |
{{ empty(old('first_name')) ? 'Sally' : old('first_name') }} |
That's it!
Comments
Post a Comment