Laravel is a popular PHP framework that offers a powerful and easy-to-use form validation system. In this article, we will guide you through the process of creating a Laravel form validation example from scratch.
Creating a Laravel Form
To start, let’s create a simple form in Laravel. We will use Laravel’s built-in form helper to create the form.
<form method="POST" action="{{ route('contact.store') }}"> @csrf <div> <label for="name">Name</label> <input type="text" name="name" id="name" value="{{ old('name') }}" required> </div> <div> <label for="email">Email</label> <input type="email" name="email" id="email" value="{{ old('email') }}" required> </div> <div> <label for="message">Message</label> <textarea name="message" id="message" required>{{ old('message') }}</textarea> </div> <button type="submit">Send</button> </form>
In the code snippet you’ve provided, a basic HTML form is created for a contact form. The method
attribute is set to “POST”, which means that the form data will be submitted to the server using the HTTP POST method. The action
attribute is set to the route name “contact.store”, which means that the form data will be submitted to the store
method of the ContactController
.
Inside the form, there are three input fields for the user’s name, email, and message. Each field has a corresponding label
element that describes the purpose of the field. The name
attribute is set to a unique identifier for each field, which will be used to access the field’s value on the server-side. The id
attribute is used to associate the label
element with its corresponding input field, which allows the user to click on the label
element to focus on the input field.
Each field also has a value
attribute that is set to old('name')
, old('email')
, and old('message')
respectively. This is a Laravel helper function that retrieves the old input values from the previous form submission. This is useful in case the form submission fails validation and the user is redirected back to the form with error messages. The old input values are repopulated in the form so the user doesn’t have to re-enter them.
The required
attribute is also set on each input field, which means that the user must enter a value in that field before submitting the form.
Finally, there is a button
element with a type
attribute set to “submit”. This is the button that the user clicks to submit the form data to the server.
In the above code, we have created a form that includes three input fields – Name, Email, and Message. We have also added a CSRF token to protect against cross-site request forgery attacks.
Creating Validation Rules
Next, we will define the validation rules for our form. Laravel provides a clean and easy-to-use way of defining validation rules using the validate()
method.
public function store(Request $request) { $validatedData = $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|email|max:255', 'message' => 'required|string|max:500', ]); // ... }
The code you’ve provided is the store
method of a Laravel controller that handles form submissions for the contact form.
The method accepts an instance of the Illuminate\Http\Request
class as a parameter, which represents the incoming HTTP request containing the form data.
Inside the method, the validate
method is called on the $request
object. This method validates the form data against a set of validation rules defined in an associative array passed as an argument. In this case, there are three validation rules defined for the name
, email
, and message
fields respectively.
The validation rules state that each of these fields is required and must be of a certain data type and maximum length. The string
rule means that the field must be a string of characters, while the email
rule specifies that the field must be a valid email address. The max
rule specifies the maximum length of the field in characters.
If any of the validation rules fail, Laravel will automatically redirect the user back to the form with the appropriate error messages. If all the validation rules pass, the $validatedData
variable will contain an associative array of the validated form data, which can then be used by the controller to perform further actions, such as saving the data to a database or sending an email.
In the above code, we have defined the validation rules for each field in our form. We have required the name, email, and message fields to be filled out, and set the maximum length for each field.
Displaying Validation Errors
If any of the fields fail validation, Laravel will automatically redirect the user back to the form with the validation errors. We can use the $errors
variable in our view to display these errors to the user.
<div> <label for="name">Name</label> <input type="text" name="name" id="name" value="{{ old('name') }}" required> @if ($errors->has('name')) <p>{{ $errors->first('name') }}</p> @endif </div>
In the code snippet you’ve provided, a validation error message is displayed next to the “Name” input field if there is an error with the user’s input.
The @if
statement checks if there is an error message associated with the “name” field. If there is, it displays the error message using the Laravel first()
method to retrieve the first error message for that field.
The errors
variable is available in Laravel’s Blade templates and contains any validation errors that were triggered during the form submission. If there were validation errors, the old()
helper function repopulates the input fields with the previously submitted values, and the errors
variable contains the error messages that were triggered. This allows you to display error messages next to the relevant input fields to help the user correct their input.
By including this code in each input field div, you can display validation error messages next to each input field that has an error.
In the above code, we have checked if the $errors
variable has an error message for the name field. If so, we display the error message to the user.
Final Thoughts
Laravel’s form validation system is powerful and easy to use. By following the steps outlined in this article, you should now be able to create your own Laravel form validation example from scratch. Remember to always validate user input to ensure the security and integrity of your application.
Handling Validation Errors
Laravel makes it easy to handle validation errors. When validation fails, Laravel will automatically redirect the user back to the form with an error message bag that contains all the validation errors. You can access this error message bag using the $errors
variable in your view.
To display the validation errors in your view, you can use the has()
and first()
methods on the $errors
variable. The has()
method checks if the error message bag has any errors for a given field, and the first()
method returns the first error message for the given field.
Here’s an example of how to display the validation errors for the email field:
<div> <label for="email">Email</label> <input type="email" name="email" id="email" value="{{ old('email') }}" required> @if ($errors->has('email')) <p>{{ $errors->first('email') }}</p> @endif </div>
In the code snippet you’ve provided, a validation error message is displayed for the “email” input field.
The @if
statement checks if the $errors
object contains an error message for the “email” field. If it does, then the error message is displayed using the {{ $errors->first('email') }}
function call.
The $errors
object is a Laravel helper object that is available in the view when validation fails. It contains all the error messages for the form fields that failed validation. The first()
method is used to retrieve the first error message for a specific field, which is then displayed to the user.
This is a useful feature because it allows the user to see exactly which field(s) failed validation and why. It also helps improve the user experience by providing clear and concise error messages.
In the above code, we first check if the $errors
variable has any errors for the email field using the has()
method. If there are errors, we display the first error message using the first()
method.
Customizing Error Messages
By default, Laravel will use a generic error message for each validation rule. For example, the required
rule will generate the error message “The [field] field is required.”
However, you can customize the error messages for each validation rule to make them more specific to your application. To customize the error messages, you can use the messages()
method on the validator instance.
Here’s an example of how to customize the error message for the email field:
$validatedData = $request->validate([ 'email' => 'required|email|max:255', ], [ 'email.required' => 'The email address field is required.', 'email.email' => 'The email address must be a valid email address.', 'email.max' => 'The email address must not exceed 255 characters.', ]);
This code snippet is an example of how to perform form validation in a Laravel controller. It uses the validate
method of the $request
object to validate the form data.
In this specific example, the validation rules are defined for the email
field. The required
rule means that the email
field must be present and not empty. The email
rule means that the email
field must contain a valid email address format. The max
rule means that the email
field must not exceed 255 characters in length.
The second argument to the validate
method is an array of custom error messages. These messages will be used if any of the validation rules fail. In this example, custom error messages are defined for each of the validation rules that apply to the email
field.
If the form data passes validation, the $validatedData
variable will be populated with an array of the validated form data. If the form data fails validation, Laravel will automatically redirect the user back to the previous page with the error messages displayed.
In the above code, we define the validation rules for the email field as before. However, we also pass a second argument to the validate()
method, which is an array of custom error messages. Each error message is associated with a specific validation rule for the email field.
Conclusion
In this article, we’ve shown you how to create a Laravel form validation example from scratch. We’ve covered how to define validation rules, handle validation errors, and customize error messages. By following these steps, you can ensure that your Laravel applications are secure and free from user input errors.
This Article Ideas has been taken from the following websites; which are following:
https://www.itsolutionstuff.com/post/laravel-10-form-validation-tutorial-exampleexample.html
Laravel 10 Form Validation Example
https://laravel.com/docs/10.x/validation
https://www.softwaretestinghelp.com/laravel-forms-and-validation/
https://www.nicesnippets.com/blog/laravel-10-form-validation-example
https://www.positronx.io/how-to-create-and-validate-form-in-laravel/
https://www.laravelia.com/post/laravel-10-form-validation-using-form-request-class
Leave a Reply