Data validation is vital in software development to make sure that input data is correct before it's processed or stored. In Laravel, handling data validation is easy and flexible.
This guide will cover the basics of implementing data validation in Laravel. You'll learn how to use Laravel's built-in validation rules and how to create your own, helping you build secure and reliable applications.
Prerequisites
- Composer
- PHP 8.2
Setup project
composer create-project laravel/laravel laravel_api 11.0.3
Project structure
├─ app
│ ├─ Http
│ │ └─ Controllers
│ │ └─ UserController.php
│ └─ Models
│ └─ Users.php
├─ resources
│ └─ views
│ └─ user.blade.php
└─ routes
└─ web.php
This project structure will display only the files and folders that we plan to create or modify.
web.php
This file sets up the route URLs for the Laravel web application, specifically defining the resource URL for our UserController
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
Route::resource('/users', UserController::class);
Users.php
This file defines the user information model.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Users extends Model
{
protected $fillable = [ 'id', 'name', 'email', 'age', 'birth_date' ];
}
UserController.php
This file handles incoming requests and validates user input data.
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Validation\ValidatesRequests;
class UserController {
use ValidatesRequests;
public function index()
{
return view('user');
}
public function store()
{
$this->validate(request(), [
'id' => 'required',
'name' => 'max:10',
'email' => 'email',
'age' => 'numeric|between:1,100',
'birth_date' => 'date'
]);
return view('user', ['pass' => true]);
}
}
index()
returns the user view, which typically contains a form for user input.
store()
handles form submissions and uses the validate()
function to check the input data. If the data is valid, the method returns the user view with a pass
variable to indicate successful validation.
user.blade.php
The HTML user input form is designed to test the validation rules. It typically includes fields that correspond to the properties of the user information.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" rel="stylesheet">
<script>
function fill(valid) {
document.getElementById('id').value = (valid ? '1' : '')
document.getElementById('name').value = (valid ? 'foo' : 'my name is foo')
document.getElementById('email').value = (valid ? 'foo@mail.com' : 'mail')
document.getElementById('age').value = (valid ? '10' : '101')
document.getElementById('birth_date').value = (valid ? '01/01/2000' : '01012000')
}
</script>
</head>
<body>
<div class="container">
<div class="row mt-3">
<div class="col">
<form method="post" action="/users">
@csrf
<div class="row">
<div class="mb-3 col-12">
<label class="form-label" for="id">Id</label>
<input id="id" name="id" class="form-control form-control-sm" value="{{old('id')}}" type="number" />
@error('id')<span class="text-danger">{{$message}}</span>@enderror
</div>
<div class="mb-3 col-12">
<label class="form-label" for="name">Name</label>
<input id="name" name="name" class="form-control form-control-sm" value="{{old('name')}}" />
@error('name')<span class="text-danger">{{$message}}</span>@enderror
</div>
<div class="mb-3 col-12">
<label class="form-label" for="email">Email</label>
<input id="email" name="email" class="form-control form-control-sm" value="{{old('email')}}" />
@error('email')<span class="text-danger">{{$message}}</span>@enderror
</div>
<div class="mb-3 col-12">
<label class="form-label" for="age">Age</label>
<input id="age" name="age" class="form-control form-control-sm" value="{{old('age')}}" />
@error('age')<span class="text-danger">{{$message}}</span>@enderror
</div>
<div class="mb-3 col-12">
<label class="form-label" for="birth_date">Birth Date</label>
<input id="birth_date" name="birth_date" class="form-control form-control-sm" value="{{old('birth_date')}}" />
@error('birth_date')<span class="text-danger">{{$message}}</span>@enderror
</div>
<div class="col-12">
<input type="button" class="btn btn-sm btn-danger" >"fill(0)" value="Fill invaid data" />
<input type="button" class="btn btn-sm btn-success" >"fill(1)" value="Fill vaid data" />
<button class="btn btn-sm btn-primary">Submit</button>
</div>
@isset($pass)
<div class="alert alert-success mt-3">
Validation success!
</div>
@endisset
</div>
</form>
</div>
</div>
</div>
</body>
-
@error
displays validation errors for a specific field. -
@isset($pass)
indicates whether the input data is valid and can be used to show a validation success message.
Run project
php artisan serve
Open the web browser and goto http://localhost:8000/users
You will find this test page.
Testing
Click "Fill invalid data" and then click "Submit" to see the error messages displayed in the input form.
Click "Fill valid data" and then "Submit" again. You should see the validation success message displayed in the input form.
Conclusion
This article has covered implementing the basic form validation, helping you build reliable and user-friendly applications. Apply these practices to enhance both the robustness and usability of your Laravel projects.
Source code: https://github.com/stackpuz/Example-Validation-Laravel-11
Create a CRUD Web App in Minutes: https://stackpuz.com
Top comments (0)