Laravel validation attributes “nice names”

后端 未结 10 1787
[愿得一人]
[愿得一人] 2020-12-02 05:41

I\'m trying to use the validation attributes in \"language > {language} > validation.php\", to replace the :attribute name (input name) for a proper to read name (example: f

10条回答
  •  旧巷少年郎
    2020-12-02 06:12

    Yeahh, the "nice name" attributes as you called it was a real "issue" a few month ago. Hopefully this feature is now implemented and is very simply to use.

    For simplicity i will split the two options to tackle this problem:

    1. Global Probably the more widespread. This approach is very well explained here but basically you need to edit the application/language/XX/validation.php validation file where XX is the language you will use for the validation.

      At the bottom you will see an attribute array; that will be your "nice name" attributes array. Following your example the final result will be something like this.

      'attributes' => array('first_name' => 'First Name')
      
    2. Locally This is what Taylor Otwell was talking about in the issue when he says:

      You may call setAttributeNames on a Validator instance now.

      That's perfectly valid and if you check the source code you will see

      public function setAttributeNames(array $attributes)
      {
          $this->customAttributes = $attributes;
      
          return $this;
      }
      

      So, to use this way see the following straightforward example:

      $niceNames = array(
          'first_name' => 'First Name'
      );
      
      $validator = Validator::make(Input::all(), $rules);
      $validator->setAttributeNames($niceNames); 
      

    Resources

    There is a really awesome repo on Github that have a lot of languages packages ready to go. Definitely you should check it out.

    Hope this helps.

提交回复
热议问题