0
0
Laravelframework~5 mins

Request validation basics in Laravel

Choose your learning style9 modes available
Introduction

Request validation helps check user input before saving or using it. It stops wrong or harmful data early.

When a user submits a form with data like name or email.
When an API receives data from another app or service.
When you want to make sure required fields are filled.
When you want to limit input length or format (like a phone number).
When you want to give clear error messages if input is wrong.
Syntax
Laravel
public function store(Request $request)
{
    $validated = $request->validate([
        'field_name' => 'required|string|max:255',
        'email' => 'required|email',
    ]);

    // Use $validated data
}

The validate method checks the rules and stops if input is invalid.

Rules are written as strings separated by pipes |.

Examples
This checks that username is required, only letters and numbers, and length between 3 and 20.
Laravel
$request->validate([
    'username' => 'required|alpha_num|min:3|max:20',
]);
This allows age to be empty or an integer 18 or older.
Laravel
$request->validate([
    'age' => 'nullable|integer|min:18',
]);
This checks email is required, valid format, and unique in users table.
Laravel
$request->validate([
    'email' => 'required|email|unique:users,email',
]);
Sample Program

This controller method checks the input for name, email, and password. It stops if any rule fails. If all pass, it returns a success message with the validated data.

Laravel
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

        // Imagine saving user here

        return response()->json([
            'message' => 'User created successfully!',
            'data' => $validated
        ]);
    }
}
OutputSuccess
Important Notes

Validation errors automatically redirect back with messages in web apps.

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

Use Laravel's built-in rules to cover many common cases easily.

Summary

Request validation checks user input early to keep data safe and correct.

Use the validate method with rules to define what input is allowed.

Validation stops the request if input is wrong and shows helpful errors.