DEV Community

Cover image for Laravel Form Request Validation
Code Of Accuracy
Code Of Accuracy

Posted on

Laravel Form Request Validation

One of the key features of Laravel is its support for form request validation, which allows you to easily validate incoming HTTP requests.

When you create a form in your Laravel application, you can define a corresponding Form Request class that encapsulates the validation logic for that form. The Form Request class extends the base Laravel request class, and includes a set of validation rules that are applied to the incoming request data.

Here's an example of a simple Form Request class that validates a user's name and email address:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ContactFormRequest extends FormRequest
{
    public function rules()
    {
        return [
            'name' => 'required|min:3',
            'email' => 'required|email',
        ];
    }
}

Enter fullscreen mode Exit fullscreen mode

In this example, the rules() method returns an array of validation rules for the form fields. The 'name' => 'required|min:3' rule specifies that the name field is required and must have at least 3 characters, while the 'email' => 'required|email' rule specifies that the email field is required and must be a valid email address.

Once you've defined your Form Request class, you can use it in your controller method to validate the incoming request. Here's an example:

<?php

namespace App\Http\Controllers;

use App\Http\Requests\ContactFormRequest;

class ContactController extends Controller
{
    public function store(ContactFormRequest $request)
    {
        // The incoming request data has already been validated
        // Do something with the validated data...
    }
}

Enter fullscreen mode Exit fullscreen mode

In this example, the store() method accepts a ContactFormRequest instance as its argument. Laravel automatically validates the incoming request data using the rules defined in the ContactFormRequest class, and passes the validated data to the store() method.

Using Laravel's form request validation feature can help you write cleaner and more maintainable code, by separating your validation logic from your controller code. It can also help you ensure that your application's data is consistent and valid, which can improve the overall user experience.

Top comments (0)