Last active
October 14, 2024 12:50
-
-
Save PierreLebedel/045e07ebc4333e52937a953af2284e45 to your computer and use it in GitHub Desktop.
Pluck Laravel collection by unique field (Typically User's First Name)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public function boot(): void | |
{ | |
Collection::macro('pluckUnique', function (string $firstAttribute, string $secondAttribute, $glue = null) { | |
return $this->map(function ($item) use ($firstAttribute, $secondAttribute) { | |
$item->firstAttributeCleaned = Str::lower($item->{$firstAttribute}); | |
$item->secondattributeCleaned = Str::lower($item->{$secondAttribute}); | |
return $item; | |
})->mapWithKeys(function ($value, $key) use ($firstAttribute, $secondAttribute, $glue) { | |
if($glue) $key = $value->{$glue}; | |
if( $this->where('firstAttributeCleaned', $value->firstAttributeCleaned)->count() > 1 ){ | |
$secondAttributeLetter = Str::substr($value->secondattributeCleaned, 0, 1); | |
if( | |
$this->where('firstAttributeCleaned', $value->firstAttributeCleaned) | |
->filter(fn($item) => Str::startsWith($item->secondattributeCleaned, $secondAttributeLetter)) | |
->count() > 1 | |
){ | |
return [$key => $value->{$firstAttribute}.' '.$value->{$secondAttribute}]; | |
} | |
return [$key => $value->{$firstAttribute}.' '.Str::upper($secondAttributeLetter).'.']; | |
} | |
return [$key => $value->{$firstAttribute}]; | |
}); | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{{ $users->pluckUnique('firstname', 'lastname')->implode(', ') }} | |
{{-- RENDER: unique first names OR first name + initial of last name if several identical first names OR full name if several identical first names & several identical initial of last names | |
Hugo, Tony, Sam E., Sam Albert, Sam Almost --}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment