Illuminate Validator in stand-alone non-Laravel application

illuminate-container, laravel, php, validation

Solution

Here is a solution for the current version: Laravel 5.4. The composer.json file:

`{ "name": "Validation standalone", "require": { "php": ">=5.6.4", "illuminate/validation": "5.4.*", "illuminate/translation": "5.4.*" } }`

Note that we must also require "illuminate/translation": "5.4.*". And then in your php file:

use Illuminate\Validation;
use Illuminate\Filesystem;
use Illuminate\Translation;

include 'vendor/autoload.php';

$filesystem = new Filesystem\Filesystem();
$fileLoader = new Translation\FileLoader($filesystem, '');
$translator = new Translation\Translator($fileLoader, 'en_US');
$factory = new Validation\Factory($translator);

$messages = [
    'required' => 'The :attribute field is required.',
];

$dataToValidate = ['title' => 'Some title'];
$rules = [
    'title' => 'required',
    'body' => 'required'
];

$validator = $factory->make($dataToValidate, $rules, $messages);

if($validator->fails()){
    $errors = $validator->errors();
    foreach($errors->all() as $message){
        var_dump($message);
    }
}

Here I have intentionally missed the "body" field in the data provided for validation, so that a validation error is displayed.

Problem

I'm building an API using Slim and the Illuminate Database package with Eloquent models etc. I have instantiated the database handler using Capsule as shown in the `README`. However, now I want to use the validation features on my models without installing the full Laravel suite, but I cannot quite wrap my head around the design of this library. How would I go about this? It seems like the documentation provided for Laravel is pretty much expecting that you use Laravel out of the box.

Original source