I have the method below that returns me a list of registered users:
$users = \App\Models\User::all();
It turns out that I would like to present only the initials of the names on that list.
Example:
Carlos Pereira do Nascimento = CN
Marcos Aurelio = MA
Sandra Lopes = SL
How could I do this by getting this data from the list?
Is it possible for me to treat this list by taking only the initials of the variable $ name?
For anyone looking for a simple, one-line, framework-agnostic solution:
$initials = preg_filter('/[^A-Z]/', '', $str);
You can use Laravel's accessor to get the initials modifying the following code:
public function getInitialsAttribute(){
$name = 'Carlos Pereira do Nascimento';
$name_array = explode(' ',trim($name));
$firstWord = $name_array[0];
$lastWord = $name_array[count($name_array)-1];
return $firstWord[0]."".$lastWord[0];
}
Now, you can get the initals using {{ $user->initials }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With