How to validate form data in Laravel



Image not found!!

In Laravel, form data validation is typically performed using the validation features provided by Laravel's validation system. Laravel's validation system allows you to validate incoming data from forms or other sources easily. Here's a step-by-step guide on how to validate form data in Laravel:

Step 1 : Create a Form:

Ensure you have a form in your Blade view or wherever you're collecting user input.

For example:

<form action="/submit" method="post">
  @csrf
  <input type="text" name="username" />
  <input type="email" name="email" />
  <button type="submit">Submit</button>
</form>


Step 2 : Create a Controller:
Laravel uses controllers to handle HTTP requests. Create a controller if you don't have one already. You can use the following Artisan command to generate a new controller:

php artisan make:controller FormController


Step 3 : Define Validation Rules:

In your controller, define the validation rules for the form data. This is typically done in the validate method.

For example:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FormController extends Controller
{
    public function submitForm(Request $request)
    {
        $validatedData = $request->validate([
            'username' => 'required|min:3|max:255',
            'email' => 'required|email',
        ]);

        // Process the validated data (save to the database, etc.)
        // ...

        return redirect('/success');
    }
}

In this example, the username field is required and must be between 3 and 255 characters, and the email field must be a valid email address.


Step 4 : Handle Validation Errors:

If validation fails, Laravel automatically redirects the user back to the form with the validation errors. You can display these errors in your Blade view like this:

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

Place this code in the Blade file where you display your form, typically at the top.


Step 5 : Display Success Message:

After successfully validating and processing the form data, you can redirect the user to a success page or display a success message.

return redirect('/success')->with('success', 'Form submitted successfully!');

And in your success view:

@if(session('success'))
    <div class="alert alert-success">
        {{ session('success') }}
    </div>
@endif

Now, when a user submits the form, Laravel will validate the data based on the rules you defined, and if validation fails, it will redirect the user back to the form with error messages. If validation succeeds, you can process the data as needed.



=== Happy Coding :)