Unfortunately none of the previous solutions will work, if you are planning to use Laravel's custom validation rules.
You can check out my solution in my gist.
Huge thanks to @vivanov and @Valentine-shi.
The custom Rule is calling the global trans()
function. This is why it is in the helpers.php
and registered via Composer.
This trans()
function is also used to create the validator factory.
- Add custom helper php file for global functions.
//<project-path>/src/helpers.php
<?php
use Illuminate\Filesystem\Filesystem;
use Illuminate\Translation\FileLoader;
use Illuminate\Translation\Translator;
if (!function_exists('trans')) {
function trans(string $key = null, array $replace = [], string $locale = null): Translator|array|string|null
{
$translationDir = dirname(__DIR__).'/lang';
$fileLoader = new FileLoader(new Filesystem(), $translationDir);
$fileLoader->addNamespace('lang', $translationDir);
$fileLoader->load('en', 'validation', 'lang');
$translator = new Translator($fileLoader, 'en');
$translator->setLocale('en');
$translator->setFallback('en');
if (is_null($key)) {
return $translator;
}
return $translator->get($key, $replace, $locale);
}
}
- Register it in composer.json
//<project-path>/composer.json
{
"require": {
"php": "^8.1",
"illuminate/translation": "^10.9",
"illuminate/validation": "^10.9",
},
"autoload": {
"files": [
"src/helpers.php"
]
}
}
- Add locale file
//<project-path>/lang/en/validation.php
<?php
return [
'accepted' => 'The :attribute must be accepted.',
// ... rest of the validations
// Copy it from Laravel.
];
- Create the validation factory, and use it
//<project-path>/scr/Validation/Validator.php
<?php
namespace <insert-your-namespace-here>;
use Illuminate\Validation\Factory;
class Validator
{
protected Factory $validator;
public function __construct()
{
$this->validator = new Factory(trans());
}
}
I'm pretty sure you can play with the required versions.