Submitting the form below will ensure a prompt response from us.
Laravel makes it easy to handle form validation, and when combined with Bootstrap, you can ensure that your forms not only work efficiently but also look great. Below is a step-by-step guide on implementing form validation in Laravel Bootstrap styling.
First, ensure you have a basic Laravel setup with Bootstrap included. If you haven’t installed Bootstrap, you can include it in your resources/views/layouts/app.blade.php file:
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
Then create a basic form inside a Blade view, for example, resources/views/contact.blade.php:
<form method="POST" action="{{ route('contact.submit') }}">
@csrf
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" class="form-control @error('name') is-invalid @enderror" id="name" value="{{ old('name') }}">
@error('name')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email" class="form-control @error('email') is-invalid @enderror" id="email" value="{{ old('email') }}">
@error('email')
<div class="invalid-feedback">{{ $message }}</div>
@enderror
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
In this form:
Next, you need to handle the form validation in your controller. For example, in ContactController.php:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ContactController extends Controller
{
public function showForm()
{
return view('contact');
}
public function submitForm(Request $request)
{
// Validate the request data
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email|max:255',
]);
// Process the data (for example, save it to the database)
return redirect()->route('contact.success');
}
}
In this example:
The validation errors will automatically be flashed to the session, so you can display them in the Blade view. In the above form code, we’ve already set up the @error directive to display validation error messages.
Important Notes:
You can customize the validation error messages by adding them to the resources/lang/en/validation.php file:
'custom' => [
'name' => [
'required' => 'Please enter your name.',
],
'email' => [
'required' => 'Please provide your email address.',
'email' => 'Please enter a valid email address.',
],
],
This will display custom messages for specific fields.
Submitting the form below will ensure a prompt response from us.