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

Ask a Doctor Online: A Simple Guide to Virtual Healthcare

In our fast-paced world, the traditional trip to a doctor’s office isn’t always the most practical first step when health concerns arise. Whether you are dealing with…

Read More

Best Free Programming Ebooks to Learn Software Development

Learning modern technology can feel overwhelming when tutorials are scattered across dozens of websites. Many software developers, engineering students, and IT professionals struggle to find comprehensive study…

Read More

FinOps Training: Understanding Cost Visibility and Optimization

Introduction Moving workloads to the cloud can simplify infrastructure management, but it can also introduce a new financial challenge. Teams can provision resources whenever they need them,…

Read More

The Architecture of Intelligent DataOps: From Ingestion to Automation

Introduction Modern organizations run on distributed data ecosystems. On any given day, an enterprise environment ingests, transforms, and serves petabytes of records sourced from transactional databases, external…

Read More

Transforming Data Reliability: How DataOps Platforms Drive Proactive Monitoring

Introduction Traditional monitoring focuses almost entirely on infrastructure availability and binary job execution states—whether a server is up or whether a task completed. However, modern distributed environments…

Read More

Navigating Pipeline Risks with Expert DevSecOps Consulting Services

Software delivery moves faster today than at any point in technological history. High-performing engineering organizations push code changes to production multiple times a day using automated deployment…

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