Auto-translation used

How to work with validation in Laravel

Data validation is a key aspect of web application development that ensures the correctness and security of user input. Laravel provides powerful and user-friendly data validation tools that can be easily integrated into your applications.

Laravel allows you to validate data directly in controllers using the validate method. This method accepts a request object and an array of validation rules. For example:

public function store(Request $request)
{
    $validatedData = $request->validate([
        'title' => 'required|max:255',
        'body' => 'required',
    ]);

    // Saving data in the database
}

This approach allows you to quickly and easily add validation to your controllers, ensuring that the data is validated before it is processed.

For more complex scenarios and improved code readability, Laravel suggests using Form Requests, specialized classes that encapsulate validation logic. This is especially useful when you need to reuse validation rules in different methods or controllers.

Creating a Form Request:

php artisan make:request StorePostRequest

Example of the Form Request class:

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    public function rules()
    {
        return [
            'title' => 'required|max:255',
            'body' => 'required',
        ];
    }
}

Using the Form Request in the controller:

public function store(StorePostRequest $request)
{
// The data has already been validated
    $validatedData = $request->validated();

    // Saving data in the database
}

Data validation in Laravel is a powerful tool that makes your applications more secure and reliable. Using the built-in features and creating your own rules, you can easily manage data validation and ensure the high quality of your code. You can find more detailed information and examples in the Laravel documentation.

Comments 3

Login to leave a comment