Skip to content

Instantly share code, notes, and snippets.

@WhereJuly
Last active April 2, 2023 00:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save WhereJuly/9c4416e46c1d611b1d17040fa6f25d9c to your computer and use it in GitHub Desktop.
Save WhereJuly/9c4416e46c1d611b1d17040fa6f25d9c to your computer and use it in GitHub Desktop.
Standalone Laravel 8.25 validation with genuine Laravel messages
// ...some entries
"require": {
"illuminate/validation": "^8.25",
"illuminate/translation": "^8.25"
}
// ...some more entries
// You have to initialize the validator in some class.
// This is up to you where. Here is just code you have to engage.
// As usual the use statements goes at the top of the class.
use Illuminate\Validation;
use Illuminate\Filesystem;
use Illuminate\Translation;
// Then you have to initialize the validator and add the default messages translation file.
// NB: $translationDir has to comprise the full path to your copy of the messages translation file
// from https://github.com/laravel/laravel/blob/8.x/resources/lang/en/validation.php
// So adjust the directory depth `4` in `dirname()` to reflect
// the actual location of the file on your server.
$translationDir = dirname(__DIR__, 4) . '/wj/laravel/lang';
$filesystem = new Filesystem\Filesystem();
$fileLoader = new Translation\FileLoader($filesystem, $translationDir);
$fileLoader->addNamespace('lang', $translationDir);
$fileLoader->load('en', 'validation', 'lang');
$translator = new Translation\Translator($fileLoader, 'en');
// After this messages are already incorporated into the validator.
$factory = new Validation\Factory($translator);
// Now the example use case
$dataToValidate = ['title' => 'Some title'];
$rules = [
'title' => 'required',
'body' => 'required',
];
$validator = $factory->make($dataToValidate, $rules);
// This would show the error message for missing `body` item.
if ($validator->fails()) {
$errors = $validator->errors();
foreach ($errors->all() as $message) {
var_dump($message);
}
}
// Now it is where pure enjoiment comes :))
@WhereJuly
Copy link
Author

WhereJuly commented Jan 30, 2021

Based on StackOverflow solution from @vivanov and this blog post from Jeff.

For details as well see my original answer on StackOverflow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment