How to handle form submissions and validation errors in Blade templates in Laravel?

To handle form submissions and validation errors in Blade templates in Laravel, follow these steps:

  1. Create a form in your Blade template using the 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>
  1. In your Laravel route file (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'); });
  1. In your Blade template, you can display the success message or any other response using the session flash data. For example:
@if (session('success')) <div class="alert alert-success"> {{ session('success') }} </div> @endif
  1. 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.

  2. 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.