Home > Article > Backend Development > How to Enforce Unique Validation Across Multiple Columns in Laravel?
Laravel: Achieving Unique Validation Across Multiple Table Columns
For scenarios where you have a database with tables containing multiple columns whose combination must remain unique, it becomes necessary to enforce this uniqueness constraint in your Laravel application.
One such example is a 'servers' table with 'ip' and 'hostname' columns. You want to ensure that a combination of a specific 'ip' and 'hostname' is unique, even if individual 'ip' or 'hostname' values may appear multiple times.
Solution Using Rule::unique()
To implement this validation, utilize the Rule::unique method. This method allows you to specify custom unique rules on a given set of columns. Here's an example:
<code class="php">$messages = [ 'data.ip.unique' => 'Given ip and hostname are not unique', ]; Validator::make($data, [ 'data.ip' => [ 'required', Rule::unique('servers') ->where(function ($query) use ($ip, $hostname) { return $query->where('ip', $ip) ->where('hostname', $hostname); }), ], ], $messages);</code>
Explanation
By implementing this rule, you effectively ensure that your application disallows duplicate combinations of 'ip' and 'hostname' in the 'servers' table.
The above is the detailed content of How to Enforce Unique Validation Across Multiple Columns in Laravel?. For more information, please follow other related articles on the PHP Chinese website!