0
0
Laravelframework~5 mins

Validate method on request in Laravel

Choose your learning style9 modes available
Introduction

The validate method on a request helps check if the data sent by a user is correct and safe before using it.

When a user submits a form and you want to make sure all required fields are filled.
When you need to check if an email address is valid before saving it.
When you want to ensure a password meets certain rules like length or characters.
When you want to stop bad or incomplete data from entering your app.
When you want to give clear error messages if the user made a mistake.
Syntax
Laravel
$request->validate([
    'field_name' => 'rule1|rule2|rule3',
    'another_field' => 'rule',
]);

The validate method takes an array where keys are field names and values are rules as strings separated by |.

If validation fails, Laravel automatically redirects back with error messages.

Examples
This checks that the email is present and valid, and the password is at least 8 characters.
Laravel
$request->validate([
    'email' => 'required|email',
    'password' => 'required|min:8'
]);
This requires a name that is a string up to 255 characters, and an optional age that must be an integer 18 or older if given.
Laravel
$request->validate([
    'name' => 'required|string|max:255',
    'age' => 'nullable|integer|min:18'
]);
Sample Program

This controller method uses validate to check user input. If the data is good, it returns a JSON message with the valid data.

Laravel
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'username' => 'required|string|max:20',
            'email' => 'required|email',
            'password' => 'required|min:6'
        ]);

        // If validation passes, $validated contains only valid data
        return response()->json(['message' => 'User data is valid', 'data' => $validated]);
    }
}
OutputSuccess
Important Notes

Validation rules are very flexible and can be combined to fit many needs.

Laravel automatically sends back errors and old input if validation fails, making it easy to show messages in forms.

You can customize error messages by passing a second argument to validate.

Summary

The validate method checks user input quickly and safely.

It uses simple rules written as strings to describe what is allowed.

If data is wrong, Laravel handles sending errors back automatically.