Last active
April 2, 2023 00:23
-
-
Save WhereJuly/9c4416e46c1d611b1d17040fa6f25d9c to your computer and use it in GitHub Desktop.
Standalone Laravel 8.25 validation with genuine Laravel messages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ...some entries | |
"require": { | |
"illuminate/validation": "^8.25", | |
"illuminate/translation": "^8.25" | |
} | |
// ...some more entries |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 :)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on StackOverflow solution from @vivanov and this blog post from Jeff.
For details as well see my original answer on StackOverflow.