Using Validation Feature in Laravel: Check and Process Input Data

To validate and process input data from forms using the validation feature in Laravel, follow these steps:

 

Define Validation Rules

Start by defining the validation rules for your form fields. Laravel provides various validation rules that you can use to ensure the integrity and validity of the data.

public function store(Request $request)
{
    $validatedData = $request->validate([
        'name' => 'required|max:255',
        'email' => 'required|email|unique:users|max:255',
        'password' => 'required|min:8',
    ]);

    // Process the validated data
    $user = User::create([
        'name' => $validatedData['name'],
        'email' => $validatedData['email'],
        'password' => Hash::make($validatedData['password']),
    ]);

    // Redirect to a success page or perform other actions
    return redirect()->route('users.index')->with('success', 'User created successfully.');
}

In the example above, we define validation rules for the name, email, and password fields. The required rule ensures that the fields are not empty, the email rule validates the email format, the unique:users rule checks if the email is unique in the users table, and the max and min rules define the maximum and minimum lengths for the password field.

 

Handle Validation Results

Laravel's validation feature automatically performs the validation based on the defined rules. If the validation fails, Laravel will redirect the user back to the form with the appropriate error messages. You can retrieve these error messages in your view to display them to the user.

<!-- Display validation errors -->
@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

<!-- Create user form -->
<form method="POST" action="{{ route('users.store') }}">
    @csrf
    <input type="text" name="name" placeholder="Name" value="{{ old('name') }}">
    <input type="email" name="email" placeholder="Email" value="{{ old('email') }}">
    <input type="password" name="password" placeholder="Password">
    <button type="submit">Create User</button>
</form>

In the above code, we check if there are any validation errors and display them in an alert box. The old() function is used to repopulate the form fields with the previously entered values if there was a validation error.

 

By following this example, you can validate and process input data from forms using the validation feature in Laravel. This ensures that the data meets your defined rules and helps maintain data integrity in your application.