April 30, 2018

Custom Validation Attributes in Laravel

<p>Recently, I was working on some <a href="https://laravel.com/docs/5.6/validation">Laravel validation</a> that used the array syntax to validate fields. For example:</p> <pre><code class="language-php">$validator = Validator::make($request-&gt;all(), [ 'database_options.name' =&gt; 'required|min:3|max:64', ]);</code></pre> <p>However, in this case the error message that is returned looks like this:</p> <pre><code>The database options.name field is required.</code></pre> <p>Not ideal. The Laravel docs cover how to <a href="https://laravel.com/docs/5.6/validation#custom-error-messages">customize the error messages</a> for rules but not for the attribute names themselves.</p> <p>It turns out there is a simple solution to this issue. You can override an attributes name by passing in an array of attribute names as the fourth parameter of the <code>Validator::make</code> method.</p> <pre><code class="language-php">$attributes = [ 'database_options.name' =&gt; 'database name', ]; $validator = Validator::make($request-&gt;all(), [ 'database_options.name' =&gt; 'required|min:3|max:64', ], [], $attributes);</code></pre> <p>Now the error message should appear like this:</p> <pre><code>The database name field is required.</code></pre>