Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Initials Laravel Package

lasserafn/php-initials

Framework-agnostic PHP library to generate name initials (UTF-8 safe, including emojis). Supports constructor or fluent API to set name and initials length, generate initials, and get URL-friendly initials. Ideal for avatars, labels, and user badges.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require lasserafn/php-initials
    

    Add to composer.json if not using Composer directly:

    "require": {
        "lasserafn/php-initials": "^1.0"
    }
    
  2. Basic Usage Import the class and generate initials:

    use Lasser\Initials\Initials;
    
    $initials = Initials::from('John Doe');
    echo $initials; // Output: "JD"
    
  3. First Use Case Display user avatars with initials in a Laravel Blade view:

    // In a controller
    $userInitials = Initials::from($user->name);
    
    // In Blade
    <div class="avatar">{{ $userInitials }}</div>
    

Where to Look First

  • Documentation: Check the GitHub README (if available) for edge cases (e.g., handling middle names, non-Latin characters).
  • Source Code: Review src/Initials.php for customization options (e.g., separator, max length).

Implementation Patterns

Core Workflows

  1. Generating Initials

    // Basic
    Initials::from('Jane Elizabeth Smith'); // "JS"
    
    // With custom separator
    Initials::from('Jane Elizabeth Smith', '-'); // "J-E-S"
    
  2. Integration with Laravel

    • Service Provider: Bind the class for dependency injection:
      // app/Providers/AppServiceProvider.php
      public function register()
      {
          $this->app->singleton(Initials::class);
      }
      
    • Helper Function: Add a global helper in app/helpers.php:
      if (!function_exists('getInitials')) {
          function getInitials($name, $separator = '') {
              return \Lasser\Initials\Initials::from($name, $separator);
          }
      }
      
  3. Dynamic Avatar Generation Combine with Laravel’s Str::upper() and CSS for styled avatars:

    $initials = Str::upper(Initials::from($user->name));
    // CSS: .avatar { background: linear-gradient(to right, #ff6b6b, #4ecdc4); color: white; }
    
  4. Handling Edge Cases

    • Empty Names: Use a fallback (e.g., "N/A"):
      $initials = Initials::from($user->name ?? 'N/A');
      
    • Non-Alphabetic Names: Trim non-letters (extend the class if needed).

Integration Tips

  • Validation: Pair with Laravel’s Validator to ensure names are sanitized before processing:
    $validator = Validator::make(['name' => $request->name], [
        'name' => 'required|string|max:255',
    ]);
    
  • Caching: Cache initials for users if avatars are static:
    $initials = Cache::remember("user-{$user->id}-initials", now()->addHours(1), function() use ($user) {
        return Initials::from($user->name);
    });
    

Gotchas and Tips

Pitfalls

  1. Locale/Encoding Issues

    • The package assumes Latin characters. For non-Latin names (e.g., Cyrillic, CJK), initials may not render correctly.
    • Fix: Extend the class to filter non-alphabetic characters or use mb_substr() for multibyte support:
      mb_substr($name, 0, 1, 'UTF-8');
      
  2. Middle Name Handling

    • By default, only the first two letters are taken (e.g., "John Michael Doe" → "JM").
    • Customization: Override the getInitials() method to include/exclude middle names:
      Initials::from('John Michael Doe', '', 2); // "JMD" (3rd param = max letters)
      
  3. Separator Quirks

    • The separator is added between all initials, not just the first two. For example:
      Initials::from('John Michael Doe', '-'); // "J-M-D" (not "J-M")
      
    • Workaround: Use a single-character separator or trim excess separators post-generation.
  4. Case Sensitivity

    • Output is lowercase by default. Use Str::upper() if consistency is needed:
      Str::upper(Initials::from('john doe')); // "JD"
      

Debugging

  • Log Input/Output: Debug unexpected results by logging the input name and generated initials:
    \Log::debug('Name:', [$user->name, Initials::from($user->name)]);
    
  • Test Edge Cases: Validate with:
    • Empty strings ("").
    • Single names ("Alice""A").
    • Names with numbers/symbols ("Bob123""B").

Extension Points

  1. Custom Initials Logic Override the Initials class to implement business rules (e.g., prioritize certain names):

    class CustomInitials extends \Lasser\Initials\Initials {
        public static function from($name, $separator = '', $maxLetters = 2) {
            $parts = explode(' ', $name);
            $initials = [];
            foreach ($parts as $part) {
                if (strpos($part, ' ') !== false) { // Handle "Van" in "Van Helsing"
                    $initials[] = mb_substr($part, 0, 1);
                }
            }
            return implode($separator, array_slice($initials, 0, $maxLetters));
        }
    }
    
  2. Laravel Service Provider Binding Bind your custom class in AppServiceProvider:

    $this->app->bind(\Lasser\Initials\Initials::class, function() {
        return new \App\Services\CustomInitials();
    });
    
  3. Package Configuration If the package supported config (e.g., default separator), add to config/initials.php:

    return [
        'default_separator' => '-',
        'max_letters' => 2,
    ];
    

    Then extend the class to read these values.

Performance

  • No Overhead: The package is lightweight (~50 lines of code). No performance concerns for typical use cases.
  • Benchmark: Test with 10,000 names to ensure it meets your app’s throughput needs (should be negligible).
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky