Illuminate Validator in stand-alone non-Laravel ap

2019-04-02 11:32发布

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.

3条回答
Juvenile、少年°
2楼-- · 2019-04-02 12:10

I was just wondering the same thing, and here I am a year later finding delatbabel's answer to be seriously wanting. I did find the following Gist where spekkionu has a fairly simple setup to get you started. (It's working on my machine?? ;P ) It shows how to make the translator for the factory, etc, etc. It's all included when you import illuminate/validation with composer.

Hope it helps: https://gist.github.com/spekkionu/e9103993138e666f9f63

Best,

查看更多
男人必须洒脱
3楼-- · 2019-04-02 12:19

I hate to suggest this but the Laravel validator is probably not what you want. I suggest having a look at the validator classes in either Symfony or Zend Framework (2+). They work quite well as stand-alone validators and in fact I am using the ZF2 form classes and validator in a Laravel project at the moment because the Laravel form and validator classes are just not up to scratch.

It's probably not the answer you wanted to hear but it might save you some pain in the long term.

查看更多
不美不萌又怎样
4楼-- · 2019-04-02 12:29

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.

查看更多
登录 后发表回答