0
0
Laravelframework~5 mins

Why validation ensures data integrity in Laravel

Choose your learning style9 modes available
Introduction

Validation checks data before saving it. This stops wrong or bad data from entering your system.

When a user submits a form with their email and password.
When uploading files to make sure they are the right type and size.
When saving user profile information like age or phone number.
When accepting input that must follow specific rules, like dates or numbers.
Syntax
Laravel
request()->validate([
    'field_name' => 'required|rule1|rule2',
]);
Use pipe (|) to separate multiple validation rules for a field.
The 'required' rule means the field must be present and not empty.
Examples
This checks that the email field is filled and looks like a valid email address.
Laravel
request()->validate([
    'email' => 'required|email',
]);
This ensures age is given, is a number, and at least 18.
Laravel
request()->validate([
    'age' => 'required|integer|min:18',
]);
This checks password is present, at least 8 characters, and matches confirmation.
Laravel
request()->validate([
    'password' => 'required|min:8|confirmed',
]);
Sample Program

This controller method checks user input for name, email, and age. It ensures name and email are present and valid, email is unique, and age is optional but if given must be a number 13 or older. If validation passes, it returns a success 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([
            'name' => 'required|string|max:50',
            'email' => 'required|email|unique:users,email',
            'age' => 'nullable|integer|min:13',
        ]);

        // Normally save user here
        return response()->json(['message' => 'User data is valid', 'data' => $validated]);
    }
}
OutputSuccess
Important Notes

Validation helps keep your database clean and reliable.

Laravel automatically redirects back with errors if validation fails in web routes.

Always validate data coming from users or external sources.

Summary

Validation checks data before saving to keep it correct.

Use Laravel's validate() method with rules to enforce data formats.

This prevents bad data and helps your app work smoothly.