While creating social media applications or blog platforms sometimes requirements arise for showing Acronyms of user names or some titles. In this post, we will generate string Acronyms using koenhendriks/laravel-str-acronym.
The Laravel Str Acronym provides a macro for generating acronyms from strings in Laravel projects using the Str helper and also supports the Stringable class.
For example, we are working on the admin panel and we went to show initials/Acronyms of first name and last name when the user profile picture is not available or uploaded.
Let’s start by installing the package. Here, we will install the package using Composer. Open your terminal and enter the below command:
composer require koenhendriks/laravel-str-acronym
Once installation is completed. We can start using this package. For this example, we will use it in the default user model to generate the initials of the user’s name. Here, we will create a new accessor for greeting initials.
Open User model and modify:
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Support\Str;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
protected $fillable = [
'name',
'email',
'password',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
protected function initials(): Attribute
{
return Attribute::make(
get: fn () => Str::acronym($this->name),
);
}
}
Here, we have created an accessor method by initials as a name. Which will convert user names into acronyms using Str facade. However, you can perform the same action using a Stringable object or add a delimiter character too.
Let’s modify our accessor to add . as a delimiter.
protected function initials(): Attribute
{
return Attribute::make(
get: fn () => Str::acronym($this->name, '.'),
);
}
In the first example, It will convert “Code Wolfy” into CW while in the second one, it will convert it to C.W.
Conclusion
In this post, you learned how to generate string acronyms in Laravel using macros, making it easy to create initials or short identifiers and reuse the logic across your app.
You have seen how to generate string acronyms in Laravel, and for handling cross-origin requests, you can also check our guide on how to enable CORS in Laravel.