我可以通过 Laravel 5.1 中的自定义请求对象在验证后恢复输入字段值吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31310894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I restore the input field values after validation through custom request objects in Laravel 5.1?
提问by Homo Sapien
Let's say I have a simple contact form.
假设我有一个简单的联系表格。
<form action="/message" method="post">
{!! csrf_field() !!}
<div class="form-group">
<label>Name: </label>
<input type="text" name="name" class="form-control">
</div>
<div class="form-group">
<label>Email: </label>
<input type="email" name="email" class="form-control">
</div>
<div class="form-group">
<label>Your Message: </label>
<textarea name="message" class="form-control"></textarea>
</div>
<div class="form-group">
<button class="btn btn-primary">Submit Message</button>
</div>
</form>
Here is my controller to handle that request:
这是我处理该请求的控制器:
public function sendMessage(ContactRequest $request)
{
dd($request->all());
}
Notice that I am injecting ContactRequest
object, so the validation is working perfectly.
请注意,我正在注入ContactRequest
对象,因此验证工作正常。
The Problem
问题
How can I restore the old input values in the contact form? So that the user wouldn't have to refill all of the fields.
如何恢复联系表单中的旧输入值?这样用户就不必重新填写所有字段。
回答by igs013
If the ContactRequest validation fails you will be redirected to your form with the errors and also the old input.
如果 ContactRequest 验证失败,您将被重定向到包含错误和旧输入的表单。
So just use {{ old('field') }}in your blade file.
所以只需在您的刀片文件中使用{{ old('field') }}。
Example for your code:
您的代码示例:
<form action="/message" method="post">
{!! csrf_field() !!}
<div class="form-group">
<label>Name: </label>
<input type="text" name="name" value="{{ old('name') }}" class="form-control">
</div>
<div class="form-group">
<label>Email: </label>
<input type="email" name="email" value="{{ old('email') }}" class="form-control">
</div>
<div class="form-group">
<label>Your Message: </label>
<textarea name="message" class="form-control">{{ old('message') }}"</textarea>
</div>
<div class="form-group">
<button class="btn btn-primary">Submit Message</button>
</div>
回答by MaGnetas
you can use "old input" method:
您可以使用“旧输入”方法:
$request->flash(); //to put the posted data to session
and
和
$username = $request->old('username'); //to get the values you previously stored
If you're doing a redirect 8back to your form) then you can flash it this way:
如果您正在将 8back 重定向到您的表单),那么您可以通过以下方式进行闪烁:
return redirect('form')->withInput();
It is even easier to get the old values in your blade template this way:
通过这种方式在您的刀片模板中获取旧值更容易:
{{ old('username') }}
More about the "old input" way can be found here
可以在此处找到有关“旧输入”方式的更多信息