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.
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.
You should add all your validation logic in the passes() function. It should return true or false based on the logic you have written in the function. The message() function returns a string that specifies the error message to be displayed in case the validation fails.
XHR Requests & Validation When using the validate method during an XHR request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.
Laravel Form Request class comes with two default methods auth() and rules() . You can perform any authorization logic in auth() method whether the current user is allowed to request or not. And in rules() method you can write all your validation rule.
After checking if the request failed to pass validation, you may use the withErrors method to flash the error messages to the session. When using this method, the $errors variable will automatically be shared with your views after redirection, allowing you to easily display them back to the user.
If the ContactRequest validation fails you will be redirected to your form with the errors and also the old input.
So just use {{ old('field') }} in your blade file.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With