Struggled with detecting duplicate values within an array
Ever struggled with detecting duplicate values within an array? Laravel's 'distinct' validation rule provides a clean and efficient solution, eliminating the need for manual checks.
<?php
use Illuminate\Support\Facades\Validator;
$usernames = [
['username' => 'tonystark'],
['username' => 'brucebanner'],
['username' => 'thor'],
['username' => 'tonystark'], // Duplicate value
];
// Instead of this
$filteredCount = collect($usernames)->unique('username');
$result = $filteredCount->count() !== collect($usernames)->count();
// Use this
Validator::make($usernames, ['*.username' => 'distinct:strict'])->fails();