Simplifying Form Validation in Laravel with Form Requests

Creating a Form Request

To get started, let’s imagine we have a form for creating blog posts. We want to validate the title and content fields. To create a Form Request class, open your terminal and run the following Artisan command:

php artisan make:request CreatePostForm

This command generates a file named CreatePostForm.php in the app/Http/Requests directory.

Defining Validation Rules

Open the newly created CreatePostForm.php file. This class contains two methods: authorize() and rules().

The authorize() method typically checks if the current user has the authority to submit the form. Since we want any authenticated user to submit a post, we can simply return true:

public function authorize()
{
    return true;
}

The rules() method defines the validation rules as an associative array. The array keys correspond to form field names, and the values define the validation rules. For example, to make the ‘title’ and ‘content’ fields required, define the rules like this:

public function rules()
{
    return [
        'title' => 'required',
        'content' => 'required'
    ];
}

Your CreatePostForm.php should now look something like this:

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CreatePostForm extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'title' => 'required',
            'content' => 'required'
        ];
    }
}

Using the Form Request

With your Form Request class in place, you can integrate it into your controller. In your controller method where you handle the form submission (e.g., PostController@store), replace the Request class with your CreatePostForm class and add a use statement to import the Form Request class:

use App\Http\Requests\CreatePostForm;

public function store(CreatePostForm $request)
{
    // Your logic for storing the validated data
}

By hinting the CreatePostForm class, Laravel will automatically validate the incoming form data based on the rules defined in the Form Request class before your controller method is executed.

Displaying Validation Errors

Now that you’ve set up form validation, let’s ensure that validation errors are properly displayed to users. In your view file, Laravel provides an $errors variable that contains all the validation errors. You can check if a field has an error and display the error message accordingly.

For example, to check if the ‘title‘ field has errors and display the first error message, you can use:

<div class="form-group @if($errors->has('title')) has-error @endif">
    <!-- Your form input for 'title' -->
    <span class="text-danger">{{ $errors->first('title') }}</span>
</div>

This code adds a has-error class to the form group if there are errors for the ‘title’ field and displays the first error message in red.

With these steps, you’ve simplified form validation in Laravel using Form Requests. It’s a clean and organized way to define validation rules and ensure your application’s data is accurate and secure.

Related Posts

Navigating Urology Treatment: From Early Symptoms to Advanced Care

Introduction Experiencing changes in urinary habits, persistent pelvic discomfort, or sudden kidney pain can feel unsettling. Many individuals delay seeking help because they are uncertain which doctor…

Read More

Modern DataOps Observability: A Practical Guide to Real-Time Data Monitoring

Introduction Organizations increasingly rely on fast event streams to power critical operational decisions. Applications across industries run on immediate analytical feedback loops: automated fraud prevention systems scoring…

Read More

Navigating Upcoming Events in Lucknow: Indie Stages, Concerts, and Art Spaces

Introduction Finding reliable, engaging activities across Lucknow often presents an unexpected challenge. Residents looking to unwind after a busy work week, college students seeking creative outlets, and…

Read More

Places to Visit in Bihar: An In-Depth Look at Regional History and Architecture

Introduction Planning a trip to eastern India often brings up questions about where to start, how connectivity works, and which heritage sites justify a visit. Bihar is…

Read More

Knee Replacement Surgery Guide: Symptoms, Surgical Options, and Physical Therapy

Introduction Persistent joint discomfort can disrupt everyday routines, making basic movements like climbing stairs, walking, or rising from a chair feel challenging. Finding effective knee treatment begins…

Read More

Complete Guide to Events in Kolkata: How to Discover What to Do

Finding something worthwhile to do across Kolkata often comes down to filtering noise rather than finding options. Between historic theatre corridors, contemporary auditorium programs, lively music venues,…

Read More
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x