If you’ve ever worked with Laravel, you’re probably familiar with its built-in validation system. It’s powerful, flexible, and allows you to easily validate data like form submissions. But what if you want to use that same validation system outside of Laravel in a plain PHP project?
In this post, we’ll show you how to use Laravel’s illuminate/validation package in a simple, standalone PHP script!
Why Use Laravel’s Validation Package?
Laravel’s validation package, illuminate/validation, is super useful because it comes with:
- Pre-built validation rules (e.g.,
required,email,min, etc.). - A clear and consistent way to handle form validation.
- Built-in error message translations.
And the best part? You don’t need to run a whole Laravel project just to use this package! You can use it in any PHP project.
How to Set It Up in a Standalone PHP Script
Here’s how you can get started.
Step 1: Install the Illuminate Validation Package
Before you can use Laravel’s validation in your project, you need to install it using Composer. Run the following command in your terminal to install the necessary packages:
composer require illuminate/validation
This will download the illuminate/validation package and its dependencies (like the translation system) into your project.
Step 2: Create the Validation Script
Now let’s write a simple PHP script that uses the illuminate/validation package.
<?php
require 'vendor/autoload.php'; // Include Composer's autoloader
use Illuminate\Validation\Factory;
use Illuminate\Translation\Translator;
use Illuminate\Filesystem\Filesystem;
// Set up translation (We're using English here)
$filesystem = new Filesystem();
$translator = new Translator($filesystem, 'en');
// Create the validation factory
$factory = new Factory($translator);
// Define the data we want to validate
$data = [
'email' => 'invalid-email', // This is an invalid email
'age' => 17, // This age is less than the minimum allowed
];
// Define the validation rules
$rules = [
'email' => 'required|email', // The email field must be a valid email
'age' => 'required|integer|min:18', // The age must be an integer and at least 18
];
// Create the validator
$validator = $factory->make($data, $rules);
// Check if validation fails or passes
if ($validator->fails()) {
// Print out any validation errors
echo "Validation failed!\n";
foreach ($validator->e<?php
require_once 'vendor/autoload.php';
use Illuminate\Translation\ArrayLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\Factory;
echo 'hello from validation file';
$loader = new ArrayLoader();
$translator = new Translator($loader, 'en');
$factory = new Factory($translator);
// $data = [
// 'email' => 'demo@demo.com',
// 'age' => 20,
// ];
$data = [
'eamil' => 'no-valid-email',
'age' => 16,
];
$rules = [
'email' => 'required|email',
'age' => 'required|min:18|integer',
];
// Create a validator instance
$validator = $factory->make($data, $rules);
// Check if validation fails or passes
if ($validator->fails()) {
// Output all errors
echo "Validation failed!\n";
foreach ($validator->errors()->all() as $error) {
echo $error . "\n";
}
} else {
echo "Validation passed!";
}rrors()->all() as $error) {
echo $error . "\n";
}
} else {
echo "Validation passed!";
}
How This Script Works:
- Autoload Dependencies:
We start by including Composer’s autoloader usingrequire 'vendor/autoload.php';. This makes sure that all the classes we installed via Composer are available to our script. - Set Up Translation:
We need to set up a translation system because Laravel’s validation errors use messages like “The email must be a valid email address.” To make it work, we initialize theTranslatorclass. It requires aFilesystemobject, which we’ll provide just to set up the translation (though we’re not loading actual language files here).- Translator: This handles translating validation error messages into the desired language. In our example, we specify
'en'for English.
- Translator: This handles translating validation error messages into the desired language. In our example, we specify
- Create a Validation Factory:
TheFactoryclass is where the magic happens. It creates the actual validation instance that will check our data against the rules we provide. - Define Data & Rules:
- Data: This is the data we want to validate (in our case, an email and an age).
- Rules: We define validation rules for each field (for example, the email must be valid, and the age must be at least 18).
- Run Validation:
Themake()method creates the validation object. Then, we call$validator->fails()to check if the data passes or fails the validation rules. If there are any errors, we loop through them and print each error message.
What Happens When We Run This?
If you run the script above with the provided data (invalid email and age under 18), it will output:
Validation failed!
The email must be a valid email address.
The age must be at least 18.
If the data passed the validation, it would simply output:
Validation passed!
Understanding the Key Concepts
- Translation System: Laravel’s validation system can provide error messages in different languages. We set up the
Translatorclass with English ('en'), but you could easily switch it to Spanish ('es') or any other language. - Factory: The
Factoryclass is used to create the validation instance. It ties everything together — the data, the rules, and the translator. - Validation Rules: Laravel’s validation rules are simple to use. You can check if a field is required, if it matches a specific format (like an email), or if it meets certain criteria (like being a minimum value).
Why Use This Outside of Laravel?
- Lightweight: You can add validation to your PHP projects without pulling in the entire Laravel framework.
- Familiarity: If you’re already familiar with Laravel, using this validation package outside of Laravel will feel comfortable.
- Flexibility: You can pick and choose which Laravel components you want to use. In this case, you’re just using the validation part.
Conclusion
By using Laravel’s illuminate/validation package in your standalone PHP scripts, you can easily validate user input with powerful, predefined rules and clear error messages. The setup might seem a little complex at first, but once you understand how the Translator and Factory classes work together, it’s pretty straightforward.
Whether you’re building a small PHP application or just need validation for a single form, this package can save you a lot of time and effort!
