Validation messages from database
Hi I am using laravel jetstream and my question is: Is there a method to get all of the validation messages from database instead from lang/en folder?
I am asking because I am trying to make multi language support for my website. Currently the database has these columns: id, lang_code (for example en, sv, hu, etc...), group_langname (main category for the translation, for example rule_messages), key (check which translation needs, for example validation_required), value (get the data).
I tried like this:
Make a service provider:
<?php
namespace App\Providers;
use App\Models\Translate;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;
class ValidationServiceProvider extends ServiceProvider
{
public function boot()
{
Validator::resolver(function ($translator, $data, $rules, $messages = [], $attributes = []) {
// Fetch custom validation messages from the database based on prefix
$customMessages = Translate::where('lang_code', 'en')->where('')->pluck('message', 'attribute')->toArray();
return new CustomValidator($translator, $data, $rules, array_merge($messages, $this->filterCustomMessages($customMessages)), $attributes);
});
}
private function filterCustomMessages(array $customMessages): array
{
// Filter messages based on the "validation_" prefix
return collect($customMessages)->mapWithKeys(function ($message, $key) {
if (strpos($key, 'validation_') === 0) {
return [$this->getAttributeWithoutPrefix($key) => $message];
}
return [];
})->toArray();
}
private function getAttributeWithoutPrefix(string $attribute): string
{
// Remove the "validation_" prefix from attributes
return str_replace('validation_', '', $attribute);
}
}
I registered in the app.php
After I created the CustomValidator.php
namespace App\Validation;
use Illuminate\Support\MessageBag;
use Illuminate\Contracts\Translation\Translator;
use Illuminate\Foundation\Http\FormRequest as Request;
use Illuminate\Validation\Validator as BaseValidator;
class CustomValidator extends BaseValidator
{
public function __construct(Translator $translator, array $data = [], array $rules = [], array $messages = [], array $attributes = [])
{
parent::__construct($translator, $data, $rules, $messages, $attributes);
}
// Override methods if needed for custom validation logic
}
In theory should work. If I am using the "required" rule and "max" then it works however with "email" it doesn't work.
In the database I registered like "validation_email" however the text is not appearing when I am writing in the form wrong way the email address. In the form part I added the input rule like this "required|email:rfc,dns". I tried also to add to the database like "validation_email:rfc,dns", "validation_email:rfc", "validation_email:dns", "validation_dns", "validation_rfc" however in the error bracket I get only "email" which is the input ID in the form. What I am doing wrong?
Please or to participate in this conversation.