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

Emoji Laravel Package

spatie/emoji

Work with emoji in PHP without relying on your IDE/font. Use the Spatie\Emoji\Emoji class to access emoji as constants or friendly camelCase methods like Emoji::grinningFace(), or fetch all emojis via Emoji::all().

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require spatie/emoji
    

    Add the service provider to config/app.php (Laravel auto-discovers it in Laravel 5.5+):

    Spatie\Emoji\EmojiServiceProvider::class,
    
  2. First Use Case: Display an emoji in a Blade view:

    // In a controller
    return view('welcome', ['emoji' => Emoji::grinningFace()]);
    
    // In Blade
    <p>{{ $emoji }}</p> <!-- Renders πŸ˜ƒ -->
    
  3. Quick Reference:

    • Single emoji: Emoji::grinningFace() β†’ πŸ˜ƒ
    • Country flag: Emoji::countryFlag('us') β†’ πŸ‡ΊπŸ‡Έ
    • All emojis: Emoji::all() β†’ Returns an associative array of all emojis.

Where to Look First

  • Package README: For method naming conventions and examples.
  • app/Providers/EmojiServiceProvider.php: If extending functionality (e.g., custom emoji sets).
  • config/emoji.php: For package-specific configurations (if any).

Implementation Patterns

Core Workflows

1. Emoji Rendering in Views

  • Blade Directives:
    // Render a single emoji
    @emoji('grinningFace')
    
    // Render a list of emojis (e.g., from a database)
    @emojiList($user->favoriteEmojis)
    
  • Dynamic Emoji Selection:
    $emoji = Emoji::fromShortcode(':thumbsup:'); // Returns πŸ‘
    

2. Validation and Sanitization

  • Form Request Validation:
    use Spatie\Emoji\Rules\Emoji;
    
    public function rules()
    {
        return [
            'comment' => ['required', new Emoji],
        ];
    }
    
  • Sanitize User Input:
    $cleanText = preg_replace('/[^\P{Emoji}]/u', '', $userInput);
    

3. Country-Specific Flags

  • Dynamic Flag Generation:
    $countryFlags = collect(['us', 'jp', 'be'])
        ->map(fn ($code) => Emoji::countryFlag($code));
    // Returns: ['πŸ‡ΊπŸ‡Έ', 'πŸ‡―πŸ‡΅', 'πŸ‡§πŸ‡ͺ']
    

4. Emoji Shortcodes (e.g., :smile:)

  • Custom Shortcode Parser:
    function parseEmojiShortcodes(string $text): string
    {
        return preg_replace_callback(
            '/:([a-z0-9_]+):/i',
            fn ($matches) => Emoji::{$matches[1]}() ?? $matches[0],
            $text
        );
    }
    
  • Usage:
    parseEmojiShortcodes('I :grinningFace: today!'); // "I πŸ˜ƒ today!"
    

5. Database Storage

  • Eloquent Casting:
    use Spatie\Emoji\Casts\Emoji;
    
    class Post extends Model
    {
        protected $casts = [
            'emoji_reaction' => Emoji::class,
        ];
    }
    
  • Query Filtering:
    Post::where('emoji_reaction', Emoji::grinningFace())->get();
    

Integration Tips

  • Laravel Nova: Extend the package to add emoji pickers in Nova toolbars.
  • Livewire/Alpine.js: Use Emoji::all() to populate a dynamic emoji picker component.
  • API Responses: Return emojis in API responses for chat/messaging apps:
    return response()->json(['message' => 'Hello! ' . Emoji::wave()]);
    
  • Markdown Processing: Integrate with packages like spatie/laravel-markdown to support emoji shortcodes in Markdown.

Gotchas and Tips

Pitfalls

  1. Method Naming Quirks:

    • Methods starting with numbers (e.g., 100Points) are supported but may cause IDE autocompletion issues. Use the CHARACTER_* constants for reliability:
      Emoji::CHARACTER_100_POINTS; // Instead of Emoji::100Points()
      
  2. Unicode Normalization:

    • Emojis may render differently across devices/browsers. Test on target platforms (e.g., iOS/Android) to ensure consistency.
    • Fix: Use mb_convert_encoding() to normalize Unicode:
      $normalizedEmoji = mb_convert_encoding(Emoji::grinningFace(), 'UTF-8', 'UTF-8');
      
  3. Flag Emoji Edge Cases:

    • Some country codes (e.g., 'bl' for Saint BarthΓ©lemy) may not render correctly due to Unicode limitations. Verify flags with Emoji::countryFlag('bl') before production use.
  4. Performance with Emoji::all():

    • Loading all emojis (1,500+ in v15.1) can be memory-intensive. Cache the result:
      $emojis = Cache::remember('all-emojis', now()->addDays(7), fn () => Emoji::all());
      
  5. IDE Autocompletion:

    • Some IDEs (e.g., PHPStorm) may not autocomplete dynamic methods (e.g., Emoji::πŸ˜ƒ()). Stick to camelCase methods or constants for reliability.

Debugging

  • Emoji Not Rendering?:

    • Ensure your font supports emoji (e.g., use Twemoji or Noto Sans Emoji).
    • Check for hidden characters with:
      var_dump(bin2hex(Emoji::grinningFace()));
      
  • Method Not Found:

    • Verify the emoji exists in the package’s Unicode list. New emojis require a package update.
  • Validation Failures:

    • The Emoji rule validates against the package’s emoji set. For custom emojis, extend the rule:
      use Spatie\Emoji\Rules\Emoji as BaseEmoji;
      
      class CustomEmoji extends BaseEmoji
      {
          protected function getAllowedEmojis(): array
          {
              return array_merge(parent::getAllowedEmojis(), ['πŸ¦„']);
          }
      }
      

Extension Points

  1. Custom Emoji Sets:

    • Override the Emoji class to add custom emojis:
      class CustomEmoji extends \Spatie\Emoji\Emoji
      {
          public static function unicorn(): string
          {
              return 'πŸ¦„';
          }
      }
      
    • Register the custom class in EmojiServiceProvider.php:
      $this->app->bind(\Spatie\Emoji\Emoji::class, CustomEmoji::class);
      
  2. Shortcode Aliases:

    • Extend the package to support custom shortcodes (e.g., :unicorn:):
      // In a service provider
      Emoji::macro('unicorn', fn () => 'πŸ¦„');
      
  3. Blade Directives:

    • Customize the @emoji directive in EmojiServiceProvider.php:
      Blade::directive('emoji', function ($expression) {
          return "<?php echo \\Spatie\\Emoji\\Emoji::{$expression}(); ?>";
      });
      
  4. Emoji Skin Tones:

    • The package includes Fitzpatrick modifiers (e.g., πŸ‘¨πŸ½). Access them via:
      Emoji::manLightSkinTone(); // πŸ‘¨πŸ½
      Emoji::manMediumLightSkinTone(); // πŸ‘¨πŸΌ
      

Configuration Quirks

  • No Config File: The package uses zero-configuration by default. All behavior is controlled via static methods.
  • PHP Version: Requires PHP 8.1+. Older versions may encounter issues with dynamic method calls (e.g., Emoji::πŸ˜ƒ()).

Pro Tips

  • Batch Processing:
    • Use Emoji::all() to preload emojis for bulk operations (e.g., migrating legacy shortcodes to emojis):
      $posts = Post::all();
      $posts->each(function ($post) {
          $post->update(['content' => str_replace(':smile:', Emoji::
      
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai