In this tutorial, we will learn how to handle forms and validate user input in Laravel. Laravel provides a powerful validation feature out-of-the-box, ensuring the integrity of user-submitted data.
What will you learn:
- Creating basic forms in Laravel
- Laravel's built-in validation features
- Validating form data
Prerequisites:
- Basic knowledge of PHP
- Basic understanding of Laravel
- Laravel environment setup
Forms are a fundamental aspect of any web application, enabling users to input data. Laravel makes it easy to validate this data before it is saved to your database.
Laravel's validation feature provides a simple and convenient way to validate incoming HTTP request with a variety of powerful validation rules.
A basic form in Laravel can be created using the Blade templating engine. Blade is a simple, yet powerful templating engine provided with Laravel.
In your blade file, you can create a form like this:
<form method="POST" action="/submit">
@csrf
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label><br>
<input type="text" id="email" name="email"><br>
<input type="submit" value="Submit">
</form>
Laravel makes it easy to perform validation on incoming data. Let's validate the data we received from the form.
public function store(Request $request)
{
$request->validate([
'name' => 'required|max:255',
'email' => 'required|email',
]);
// The incoming request is valid...
// Retrieve the validated input data...
$validated = $request->validated();
}
In this code snippet, required|max:255
means the name
field is required and must not exceed 255 characters. required|email
means the email
field is required and must be a valid email address. If the validation fails, the user will be redirected back to the form.
In this tutorial, we learned how to create a basic form in Laravel and how to use Laravel's built-in validation feature to validate the form data. The next step would be to learn how to save this data to a database.
Additional Resources
- Laravel's Validation Documentation
- Laravel's Blade Documentation
make:rule
Artisan command. The passes
method of the rule class is used to validate the attribute value. The message
method should return the validation error message that should be used when validation fails. You can find more information in the Laravel's Validation Documentation.