Skip to content

Instantly share code, notes, and snippets.

@mtvbrianking
Created September 24, 2023 17:30
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 mtvbrianking/de1624a6fbc5e68f8dbf8ea738057b0d to your computer and use it in GitHub Desktop.
Save mtvbrianking/de1624a6fbc5e68f8dbf8ea738057b0d to your computer and use it in GitHub Desktop.
Laravel validation attributes

Issue

Attribute names are replaced. E.g 'from_account_id' to 'from account id'

{
    "errors": {
        "to_account_id": [
            "The to account id field and from account id must be different."
        ],
    }
}

Option #1

Declare the attribute names in translations

$this->validate($request, [
    'from_account_id' => 'required|integer',
    'to_account_id' => 'required|integer|different:from_account_id',
]);

lang/en/validation.php

  return [
      'attributes' => [
+         'from_account_id' => 'from_account_id',
+         'to_account_id' => 'to_account_id',
      ],
  ];

Option #2

Pass the attribute names to the validator

$rules = [
    'from_account_id' => 'required|integer',
    'to_account_id' => 'required|integer|different:from_account_id',
];

$attributes = [
    'from_account_id' => 'from_account_id',
    'to_account_id' => 'to_account_id',
];

$validator = Validator::make($request->all(), $rules, $messages = [], $attributes);

$validator->validate();

Results

{
    "errors": {
        "to_account_id": [
            "The to_account_id field and from_account_id must be different."
        ],
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment