To handle form submissions and validation errors in Blade templates in Laravel, follow these steps:
form
helper provided by Laravel. For example:<form method="POST" action="/submit">
@csrf
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" class="form-control">
@error('name')
<span class="text-danger">{{ $message }}</span>
@enderror
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email" class="form-control">
@error('email')
<span class="text-danger">{{ $message }}</span>
@enderror
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
web.php
), define the route to handle the form submission and validation. For example:use Illuminate\Http\Request;
Route::post('/submit', function (Request $request) {
$validatedData = $request->validate([
'name' => 'required|min:2|max:255',
'email' => 'required|email|max:255',
]);
// Perform other logic or save data
return redirect('/success');
});
@if (session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
To handle server-side validation errors, you can use the @error
directive provided by Laravel. If there are any validation errors, the error message will be displayed next to the corresponding input field.
You can also pre-fill the form fields with the old input by using the old
helper provided by Laravel. For example:
<input type="text" name="name" class="form-control" value="{{ old('name') }}">
This will populate the input field with the value entered by the user if there is a validation error.
By following these steps, you can handle form submissions and display validation errors in your Blade templates in Laravel.