We will going to use Simple PHP Function by using preg regex function. so makes the assumption the end name will be a single word. Makes no assumption about middle names, that all just gets grouped into first name. You could use it again, on the “first name” result to get the first and middle though.

Naming Profile Avatar

Here is the code : –

@php
$uzr = Auth::user()->name;

 $name = trim($uzr);
 $last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name);
 $first_name = trim( preg_replace('#'.preg_quote($last_name,'#').'#', '', $name ) );

@endphp

<span class="profile_round"> {{$firstStringCharacter = substr($first_name, 0, 1)}} {{$firstStringCharacter = substr($last_name, 0, 1)}} </span>

CSS:

<style>
    .profile_round {
    width: 30px;
    height: 30px;
    text-align: center;
    display: grid;
    align-items: center;
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
    text-transform: capitalize;
    border-radius: 50%;
    box-shadow: 0 0 0 10px rgb(255 103 27 / 5%);
    font-size: 1rem;
    font-weight: 800;
    margin-top: 5px;
    margin-left: 13px;
    }
    </style>

Code Explain :

At first we will get auth or logged in user fullname.

$name = trim($uzr->name); //PHP trim function will Remove char from both sides of a string (“He” in “Hello” and “d!” in “World”):

after that we will get first and last name of the user in $last_name and $first_name variable

then we will use substr() function, tha will returns the extracted part of a string.

Result:

AB

This is useful when user not uploaded any profile picture, so it will show his/her first and last name letter as profile picture. Add CSS to make it round profile icon.

Tagged in: