Skip to content

Instantly share code, notes, and snippets.

@Otisz
Last active May 4, 2023 12:19
Show Gist options
  • Save Otisz/17b202058470057617714bb626f21a6b to your computer and use it in GitHub Desktop.
Save Otisz/17b202058470057617714bb626f21a6b to your computer and use it in GitHub Desktop.
Laravel's validation outside of Laravel

How to use Laravel's validation outside of Laravel

Based on this SO question here is my implementation.

What is the difference?

The solutions in the SO question does not use custuom validation rules.

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.

Example

Here is fully working PHP SDK with my solution: https://github.com/TMRW-Life/ntak.guru-php-sdk

Credits

//<project-path>/composer.json
{
"require": {
"php": "^8.1",
"illuminate/translation": "^10.9",
"illuminate/validation": "^10.9",
},
"autoload": {
"files": [
"src/helpers.php"
]
}
}
//<project-path>/src/helpers.php
<?php
use Illuminate\Filesystem\Filesystem;
use Illuminate\Translation\FileLoader;
use Illuminate\Translation\Translator;
if (!function_exists('trans')) {
/**
* Translate the given message.
*
* This code is not really optimal outside of Laravel (without IOC container),
* but it should not be used in production anyway.
*
* @param string|null $key
* @param array $replace
* @param string|null $locale
* @return \Illuminate\Contracts\Translation\Translator|string|array|null
*/
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);
}
}
//<project-path>/lang/en/validation.php
<?php
return [
'accepted' => 'The :attribute must be accepted.',
// ... rest of the validations
// Copy it from Laravel.
];
//<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());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment