Laravel Validation: How To Add Form Validation In Laravel

Laravel Validation: How To Add Form Validation In Laravel

1. Basic Form Validation

In Laravel, form validation is typically done within the controller. Validation rules are defined in the validate() method, which automatically redirects back to the form with validation errors if any validation rules are not met.

Step-by-Step Process

a. Create a Form Request Validation Class (Optional)

For complex validation logic, Laravel allows you to create custom form request validation classes. This is optional, and you can simply use the validate() method directly in the controller. However, using form request validation classes keeps your controllers cleaner.

To create a custom validation request class, run the following command:

php artisan make:request StoreEmployeeRequest

This will create a new request class in the app/Http/Requests directory. In the generated class, you can define validation rules.

namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class StoreEmployeeRequest extends FormRequest { public function authorize() { // Ensure that the user is authorized to make this request return true; } public function rules() { return [ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:employees,email', 'age' => 'required|integer|min:18', 'salary' => 'required|numeric|min:0', ]; } }
  • authorize(): Determines if the user is authorized to make the request. Typically, you'll return true unless you have specific authorization logic.

  • rules(): Defines the validation rules for the form data. You can use built-in validation rules such as required, string, email, min, max, etc.

b. Using Validation Directly in the Controller

If you prefer to validate directly in the controller method, here's how you do it.

namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Employee; class EmployeeController extends Controller { public function store(Request $request) { // Validate the request data $validatedData = $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:employees,email', 'age' => 'required|integer|min:18', 'salary' => 'required|numeric|min:0', ]); // If validation passes, create the new employee Employee::create($validatedData); return redirect()->route('employees.index')->with('success', 'Employee created successfully.'); } }

In this example:

  • $request->validate() Validates the input based on the rules provided.

  • If validation fails, Laravel automatically redirects back to the previous page (usually the form) and provides error messages for each field that fails validation.

  • If validation passes, you proceed to store the data.

c. Customizing Validation Messages

You can customize the error messages by passing an optional second parameter to the validate() method. This is a key feature when you want to provide more user-friendly messages.

$request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:employees,email', 'age' => 'required|integer|min:18', 'salary' => 'required|numeric|min:0', ], [ 'name.required' => 'Please provide a name.', 'email.required' => 'The email address is required.', 'email.email' => 'Please enter a valid email address.', 'age.required' => 'Please specify the age.', 'salary.required' => 'Please provide a salary amount.', ]);

You can customize each validation rule's message using the field name and rule combination (e.g., name.required, email.email).

d. Displaying Validation Errors in Views

In your Blade view, you can easily display validation errors. Laravel automatically populates an error bag, which can be accessed using the @error directive.

Here’s an example of displaying errors for the name field:

<form method="POST" action="{{ route('employees.store') }}"> @csrf <div class="form-group"> <label for="name">Name</label> <input id="name" type="text" class="form-control @error('name') is-invalid @enderror" name="name" value="{{ old('name') }}"> @error('name') <div class="invalid-feedback"> {{ $message }} </div> @enderror </div> <!-- Similarly for other fields like email, age, salary --> <button type="submit" class="btn btn-primary">Submit</button> </form>
  • The @error directive checks if there's an error for the name field and displays the error message.

  • The old('name') helper ensures that the user’s input persists after validation fails, so the form is pre-filled with the submitted data.

2. Validation Rules

Laravel offers a wide range of validation rules that you can use to validate form input. Here are some of the most commonly used ones:

  • required: Ensures the field is not empty.

  • string: Ensures the value is a string.

  • email: Ensures the value is a valid email address.

  • unique:table,column: Ensures the value is unique in the specified database table and column.

  • min:n: Ensures the value has a minimum length (for strings) or value (for numbers).

  • max:n: Ensures the value does not exceed a maximum length (for strings) or value (for numbers).

  • integer: Ensures the value is an integer.

  • numeric: Ensures the value is numeric.

  • date: Ensures the value is a valid date.

  • confirmed: Ensures the field has a matching field (e.g., password and password_confirmation).

3. Advanced Validation

Laravel also provides powerful features for advanced validation:

a. Custom Validation Rules

You can create custom validation rules by using the Validator facade or by defining custom rule classes.

use Illuminate\Support\Facades\Validator; Validator::extend('uppercase', function ($attribute, $value, $parameters, $validator) { return strtoupper($value) === $value; }); $request->validate([ 'password' => 'required|uppercase', ]);

b. Conditional Validation

You can apply validation rules conditionally using sometimes():

$request->validate([ 'name' => 'required|string|max:255', ]); $request->validate([ 'email' => 'required|email|unique:users,email', ]); $request->sometimes('phone', 'required', function ($input) { return $input->email === null; });

This will make the phone field required only if the email field is empty.

4. Handling Validation Failure

When validation fails, Laravel will automatically redirect the user back to the form and flash the error messages to the session. If you’re not using a controller and want to manually handle the validation failure, you can do it like this:

if ($validator->fails()) { return redirect()->back()->withErrors($validator)->withInput(); }Conclusion

Laravel's built-in validation system is flexible and easy to use, providing everything you need for ensuring that form data is correct. From basic validation to custom rules and advanced features, Laravel offers a robust system for validating user input.

  • Simple: You can start with the validate() method in controllers, which automatically handles error redirection.

  • Powerful: Laravel's request validation classes allow for cleaner and more organized code, especially when validation rules get complex.

  • Flexible: You can easily customize validation messages, use custom rules, and apply conditional validation.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close