Utilizing Rule::unique for Multi-Column Unique Validation in Laravel
In your Laravel application, you have a table named "servers" with two columns: "ip" and "hostname." You desire to ensure that a combination of these two columns is unique, preventing duplicate entries. While you have already implemented a validation rule for the "ip" column, you aim to expand this logic to include the "hostname" column as well.
To achieve this multi-column unique validation, you can leverage Laravel's Rule::unique method. Here's a modified version of your validation rule:
<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:
This updated validation rule will ensure that the combination of "ip" and "hostname" values is unique in the "servers" table, effectively preventing duplicate entries with the same IP and hostname.
The above is the detailed content of How to Implement Multi-Column Unique Validation Using Rule::unique in Laravel?. For more information, please follow other related articles on the PHP Chinese website!