In blade template I use {{ Auth::user()->name }} to diplay the username of the logged in user, I'd like to be able to display the initials and instead of putting the php code directly in the template which isn't very elegant I'd like to have something like {{ Auth::user()->initials }}
What's best practice for doing such? Any examples? Thanks
@AlexYa Looks like this is what I need. Could you possibly elaborate on your example? I'm not quite sure how to implement this. Refering me to the proper documentation works as well, I can't seem to find what I need. Thanks!
You can get the first letter of a string by just doing $string[0] - so for example you could just return $this->firstname[0] . $this->secondname[0] (or format it however you need).
Everything I needed was actually here. Being sick + tired isn't the best combination, had me confused. Got it working, thanks and sorry for my confusion :-)
With the new Laravel starter kits (livewire) the initials public function is used but I have firstname and lastname for users - so I needed to amend the initials script.
Think I have read the above correctly but I would appreciate someone telling me if this is;
a) okay
b) a sensible solution
c) if there is a better way given its 2025 and a lot has changed since this post was solved, because I have 2 variables specifically I think I can remove the explode - implode methods
Function in starter kits for reference
public function initials(): string
{
return Str::of($this->name)
->explode(' ')
->map(fn (string $name) => Str::of($name)->substr(0, 1))
->implode('');