Skip to content

Instantly share code, notes, and snippets.

@shahmal1yev
Last active December 7, 2023 12:47
Show Gist options
  • Save shahmal1yev/83278bdf4b886590e88cc965db8ed636 to your computer and use it in GitHub Desktop.
Save shahmal1yev/83278bdf4b886590e88cc965db8ed636 to your computer and use it in GitHub Desktop.
Dynamic Retrieval of Rules for Multilingual Fields
<?php
if (! function_exists('add_locales'))
{
function generateRules4(array $translatedFieldRules): array
{
$locales = config('translatable.locales');
$return = [];
foreach($locales as $locale) {
$return["$locale"] = ["required", "array"];
foreach ($translatedFieldRules as $name => $rules)
$return["$locale.$name"] = $rules;
}
return $return;
}
}
array:10 [ // app/Http/Requests/Folder/StoreFolderRequest.php:21
"az" => array:2 [
0 => "required"
1 => "array"
]
"az.name" => array:3 [
0 => "required"
1 => "string"
2 => "max:224"
]
"az.surname" => array:3 [
0 => "required"
1 => "string"
2 => "max:224"
]
"en" => array:2 [
0 => "required"
1 => "array"
]
"en.name" => array:3 [
0 => "required"
1 => "string"
2 => "max:224"
]
"en.surname" => array:3 [
0 => "required"
1 => "string"
2 => "max:224"
]
"ru" => array:2 [
0 => "required"
1 => "array"
]
"ru.name" => array:3 [
0 => "required"
1 => "string"
2 => "max:224"
]
"ru.surname" => array:3 [
0 => "required"
1 => "string"
2 => "max:224"
]
"parent_id" => array:3 [
0 => "required"
1 => "int"
2 => "exists:folders,id"
]
]
<?php
namespace App\Http\Requests\Folder;
use Illuminate\Foundation\Http\FormRequest;
use function PHPUnit\Framework\callback;
class StoreFolderRequest extends FormRequest
{
public function rules(): array
{
$translatedFieldRules = generateRules4([
'name' => ['required', 'string', 'max:224'],
'surname' => ['required', 'string', 'max:224']
]);
return array_merge($translatedFieldRules, [
"parent_id" => ['required', 'int', 'exists:folders,id']
]);
}
public function authorize(): bool
{
return true;
}
}
<?php
namespace App\Http\Requests\Folder;
use Illuminate\Foundation\Http\FormRequest;
class UpdateFolderRequest extends FormRequest
{
public function rules(): array
{
$translatedFieldRules = generateRules4([
'name' => ['string', 'max:224'],
'surname' => ['string', 'max:224']
]);
return array_merge($translatedFieldRules, [
"parent_id" => ['int', 'exists:folders,id']
]);
}
public function authorize(): bool
{
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment