Skip to content

Conversation

onlime
Copy link
Contributor

@onlime onlime commented Jan 13, 2022

In Jetstream laravel/jetstream#940, @geisi has introduced anonymized default profile photo url calls by only extracting the initials of a user's name. It would have been nice if he could have used an existing Laravel String helper function.

I am introducing Str::initials() for this purpose and hope it helps you in other use cases.

For those who already want to use this before it's accepted/merged, just extend Illuminate\Support\Str with this macro in your AppServiceProvider's boot() method:

        Str::macro('initials', fn($value, $sep = ' ', $glue = ' ') => trim(collect(explode($sep, $value))->map(function ($segment) {
            return $segment[0] ?? '';
        })->join($glue)));

and then just use Str::initials('Firstname Lastname') or as an Eloquent accessor in your User model:

    public function getInitialsAttribute(): string
    {
        return \Illuminate\Support\Str::initials($this->name);
    }

so you can simply use something like {{ Auth::user()->initials }}.

@onlime onlime changed the title Add Str::initials() helper to get initials of a given value [8.x] Add Str::initials() helper to get initials of a given value Jan 13, 2022
@taylorotwell
Copy link
Member

Thanks for your pull request to Laravel!

Unfortunately, I'm going to delay merging this code for now. To preserve our ability to adequately maintain the framework, we need to be very careful regarding the amount of code we include.

If possible, please consider releasing your code as a package so that the community can still take advantage of your contributions!

If you feel absolutely certain that this code corrects a bug in the framework, please "@" mention me in a follow-up comment with further explanation so that GitHub will send me a notification of your response.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants