laravel-validacion-de-datos-en-laravel

Data Validation in Laravel

  • 3 min

Laravel’s validation allows you to check request data using declarative rules.

Laravel has a built-in validation system within the Request object itself. You define the rules (what you accept) and Laravel acts as the “bad cop.”

The $request->validate() Method

Imagine we receive a product. It must have a name (required), a price (numeric), and a SKU code (which must be unique in the products table).

Old Code (Classic PHP - Nightmare):

if (empty($_POST['nombre'])) {
    $errores[] = "El nombre es obligatorio";
}
if (!is_numeric($_POST['precio'])) {
    $errores[] = "El precio debe ser número";
}
// ... connect to DB to see if the SKU exists ...
if (count($errores) > 0) {
    // Redirect and pass errors...
}
Copied!

Laravel Code (Paradise): Inside your controller method:

public function store(Request $request)
{
    // A single line (or block) that does EVERYTHING
    $validatedData = $request->validate([
        'nombre' => 'required|max:255',
        'precio' => 'required|numeric|min:0',
        'sku'    => 'required|unique:products,sku', // Automatically checks the DB!
    ]);

    // If the code reaches here, EVERYTHING is valid.
    // If it fails, Laravel stops execution right here.

    // The model must allow these fields through $fillable
    // or an equivalent mass assignment configuration.
    Product::create($validatedData);
    
    return redirect('/products');
}
Copied!

What happens if validation fails?

The brilliant thing about $request->validate() is what you don’t see. If a rule is not met (e.g., the user left the name blank):

Laravel detects the failure.

Stops the script execution immediately (it doesn’t proceed to the save line).

Redirects the user automatically to the previous page (where the form was).

Injects the errors into the session so you can display them.

Remembers the data the user entered (old input) so they don’t have to retype the entire form.

All of that automatically without writing a single if!

The Most Common Rules

Laravel has hundreds of rules ready to use. They are separated by a vertical bar |.

RuleDescription
requiredThe field cannot be empty.
emailMust be a valid email format.
numeric / integerNumbers only.
min:5 / max:255Minimum or maximum length (or numeric value).
confirmedLooks for another field named _confirmation and checks if they are equal (ideal for passwords).
unique:table,columnChecks the Database to ensure that value doesn’t already exist.
date / after:tomorrowDate validations.

Displaying Errors in the View (Blade)

Validation is useless if the user doesn’t know what they did wrong. Laravel automatically shares a $errors variable with all your views.

A. Display a general list of errors:

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
Copied!

B. Display error below each input (Recommended): Additionally, we use the old('field_name') function to pre-fill what the user typed before making the mistake.

<label>Product Name:</label>
<input type="text" name="nombre" value="{{ old('nombre') }}">

@error('nombre')
    <span style="color: red;">{{ $message }}</span>
@enderror
Copied!