Search code examples
laravelvalidationtranslation

Lavavel 8 disable translation, response with field name and rule


I have simply issue but I stucked. I need to disable translations for validators only. For example, let field name has rule max:80. When validation fails, I want to response with json:

{
    "errors": {
        "name": {
            "max": 80
        },
    },
    "status": "error"
}

Is there any way to achieve it? I made my own Translator (which extends \Illuminate\Translation\Translator) and I figured out, that I could check if translations comes from validation.php file, and replace the value with translation's key. But this solution apears to be very ugly.

EDIT: I decide to leave translations. Problem is with validation, not with translations. So I made CustomValidator class

namespace App\Overrides;

use Illuminate\Validation\Validator;

class CustomValidator extends Validator
{
    /**
     * Determine if the data passes the validation rules.
     *
     * @return bool
     */
    public function passes(): bool
    {
        return parent::passes();
    }
}

and factory for it:

namespace App\Overrides;

use Illuminate\Validation\Factory;

class ValidatorFactory extends Factory
{
    protected function resolve(array $data, array $rules, array $messages, array $customAttributes )
    {
        if (is_null($this->resolver)) {
            return new CustomValidator($this->translator, $data, $rules, $messages, $customAttributes);
        }

        return call_user_func($this->resolver, $this->translator, $data, $rules, $messages, $customAttributes);
    }
}

then I swapped the factory

namespace App\Providers;

use App\Overrides\ValidatorFactory;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->extend('validator', function () {
            return $this->app->get(ValidatorFactory::class);
        });
    }

But there is a new problem. Validation's rules used database (like "unique") throwns ecxeption: Presence verifier has not been set. Other rules doesn't.


Solution

  • $validator->failed(); is the answer.

    It contains all failed rules:

    array:2 [
      "name" => array:1 [
        "Max" => array:1 [
          0 => "80"
        ]
      ]
      "password" => array:1 [
        "Regex" => array:1 [
          0 => "/[a-z]/"
        ]
      ]
    ]