Skip to content

Instantly share code, notes, and snippets.

@sayhicoelho
Last active December 12, 2019 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sayhicoelho/93ada106bc90163a22ebb10ec791b844 to your computer and use it in GitHub Desktop.
Save sayhicoelho/93ada106bc90163a22ebb10ec791b844 to your computer and use it in GitHub Desktop.
Translate 'yesterday', 'now', 'today' and 'tomorrow' words with Laravel
<?php
namespace App\Validator;
use Carbon\Carbon;
class CustomValidator extends \Illuminate\Validation\Validator {
protected function getTimePeriods($parameter) {
$keys = array_keys(trans('validation.time_periods'));
$values = array_values(trans('validation.time_periods'));
if (!in_array($parameter, $keys)) {
$parameter = (new Carbon($parameter))->formatLocalized('%d de %B');
}
return str_replace(
$keys,
$values,
$parameter
);
}
public function replaceBefore($message, $attribute, $rule, $parameters) {
return str_replace(':date', $this->getTimePeriods($parameters[0]), $message);
}
public function replaceAfter($message, $attribute, $rule, $parameters) {
return str_replace(':date', $this->getTimePeriods($parameters[0]), $message);
}
}
<?php
return [
// ...
'time_periods' => [
'yesterday' => 'ontem',
'now' => 'agora',
'today' => 'hoje',
'tomorrow' => 'amanhã',
],
];
<?php
namespace App\Providers;
use Validator;
use Illuminate\Support\ServiceProvider;
use App\Validator\CustomValidator;
class ValidatorServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
Validator::resolver(function($translator, $data, $rules, $messages) {
return new CustomValidator($translator, $data, $rules, $messages);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment