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 template:

    {{ \Spatie\Emoji\Emoji::grinningFace() }}
    

    Or use the Blade directive:

    @emoji('grinningFace')
    
  3. Quick Validation: Check if a string contains valid emojis:

    use Spatie\Emoji\EmojiValidator;
    
    $validator = new EmojiValidator();
    $isValid = $validator->validate('Hello ๐Ÿ˜Š'); // true
    

Where to Look First

  • Class Reference: Spatie/Emoji GitHub โ†’ src/Emoji.php for all available methods (e.g., grinningFace(), countryFlag('us')).
  • Blade Directives: Documentation for @emoji and @emojiList.
  • Changelog: v4.1.2 for Unicode 15.1 support and PHP 8.2 compatibility.

Implementation Patterns

Core Workflows

1. Emoji Rendering in Templates

  • Blade Directives (Recommended for Views):
    @emoji('thumbsUp') <!-- Outputs: ๐Ÿ‘ -->
    @emojiList(['grinningFace', 'heartEyes']) <!-- Outputs: ๐Ÿ˜ƒ๐Ÿ˜ -->
    
  • PHP Methods (For Logic/Helpers):
    $emoji = \Spatie\Emoji\Emoji::thumbsUp();
    return response()->json(['emoji' => $emoji]);
    

2. Shortcode-to-Emoji Conversion

  • Custom Helper (e.g., :smile: โ†’ ๐Ÿ˜Š):
    function convertShortcodesToEmojis(string $text): string {
        $shortcodes = [
            ':smile:' => 'grinningFace',
            ':heart:' => 'heart',
        ];
        foreach ($shortcodes as $shortcode => $method) {
            $text = str_replace($shortcode, \Spatie\Emoji\Emoji::$method, $text);
        }
        return $text;
    }
    
  • Use Case: Comments, chat messages, or Markdown processors.

3. Country Flags

  • Dynamic Flag Generation:
    $flag = \Spatie\Emoji\Emoji::countryFlag('jp'); // ๐Ÿ‡ฏ๐Ÿ‡ต
    
  • Use Case: User profiles, location-based features, or multilingual apps.

4. Validation

  • Form Requests:
    use Spatie\Emoji\EmojiValidator;
    
    public function rules() {
        return [
            'comment' => ['required', new EmojiValidator],
        ];
    }
    
  • API Payloads:
    $validator = Validator::make($request->all(), [
        'message' => ['required', new EmojiValidator],
    ]);
    

5. Database Storage

  • Eloquent Casting (Store emoji shortcodes as strings, render on-the-fly):
    use Spatie\Emoji\Emoji;
    
    class Comment extends Model {
        protected $casts = [
            'emoji_reaction' => 'string', // Stores ":thumbsUp"
        ];
    
        public function getEmojiReactionAttribute($value) {
            return Emoji::{$value}(); // Renders ๐Ÿ‘
        }
    }
    

Integration Tips

  • Laravel Events: Trigger emoji processing in Creating/Updating model events:
    public function creating(Model $model) {
        $model->content = convertShortcodesToEmojis($model->content);
    }
    
  • API Responses: Normalize emoji responses for consistency:
    return response()->json([
        'message' => 'Hello!',
        'emoji' => Emoji::wave(), // ๐Ÿ‘‹
    ]);
    
  • Caching: Cache Emoji::all() if used frequently in loops (e.g., emoji picker UI):
    $emojis = Cache::remember('all-emojis', now()->addHours(1), function() {
        return Emoji::all();
    });
    

Gotchas and Tips

Pitfalls

  1. Method Naming Quirks:

    • Methods starting with numbers (e.g., 100Points()) may cause IDE autocompletion issues. Use the CHARACTER_* constants instead:
      Emoji::CHARACTER_100_POINTS; // ๐Ÿ†
      
    • Fix: Prefer Emoji::all() for dynamic access or IDE-friendly constants.
  2. Unicode Normalization:

    • Emojis may render differently across devices/fonts. Test on target platforms (e.g., iOS/Android browsers).
    • Workaround: Use mb_convert_encoding() for consistent output:
      $normalized = mb_convert_encoding(Emoji::grinningFace(), 'UTF-8', 'UTF-8');
      
  3. Flag Emoji Edge Cases:

    • Some regions (e.g., bl for Saint Barthรฉlemy) may not render correctly. Verify with Emoji::countryFlag('bl').
    • Tip: Maintain a fallback list of supported flags in your app.
  4. Performance in Loops:

    • Avoid calling Emoji::all() in tight loops. Cache the result or use specific methods:
      // Bad: Emoji::all() in a 1000-item loop
      // Good: Pre-fetch needed emojis
      $emojis = [Emoji::grinningFace(), Emoji::heart()];
      
  5. Blade Directive Scope:

    • @emoji directives only work in Blade templates. For non-Blade contexts (e.g., API responses), use PHP methods directly.

Debugging

  • Invalid Emoji Methods:

    • If Emoji::unknownMethod() fails, check the full list or use Emoji::all() to inspect available methods.
    • Debug Tip: Enable Laravelโ€™s debugbar to inspect the Emoji class constants.
  • Font Rendering Issues:

    • If emojis display as boxes, ensure your server/IDE uses a Unicode-compatible font (e.g., Noto Color Emoji, Segoe UI Emoji).
    • Test: Run echo Emoji::grinningFace(); in artisan tinker to verify local rendering.

Extension Points

  1. Custom Emoji Sets:

    • Extend the Emoji class to add project-specific emojis:
      class CustomEmoji extends \Spatie\Emoji\Emoji {
          public static function customEmoji() {
              return '๐Ÿš€'; // Your custom emoji
          }
      }
      
    • Tip: Override the all() method to merge custom emojis:
      public static function all() {
          return array_merge(parent::all(), [
              'customEmoji' => '๐Ÿš€',
          ]);
      }
      
  2. Dynamic Shortcode Parsing:

    • Use regex to parse custom shortcodes (e.g., {{emoji}}):
      preg_replace_callback('/\{\{emoji:(\w+)\}\}/', function ($matches) {
          return Emoji::{$matches[1]}();
      }, $text);
      
  3. Emoji Skin Tones:

    • The package supports Fitzpatrick modifiers (e.g., grinningFaceLightSkinTone()). Document these in your appโ€™s UI for consistency.
  4. Localization:

    • Combine with Laravelโ€™s localization to map emojis to language-specific meanings (e.g., ๐Ÿ‘ = "good" in English, "okay" in Japanese).
    • Example:
      $translation = __("emoji.thumbs_up.{$locale}");
      

Configuration Quirks

  • No Config File: The package is zero-config. All behavior is controlled via static methods.
  • PHP Version: Requires PHP โ‰ฅ8.1. Test with php -v before integration.
  • Composer Autoload: Ensure composer dump-autoload is run after adding custom emoji classes.

Pro Tips

  1. Emoji Picker UI:
    • Use Emoji::all() to populate a dropdown or grid:
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.
codraw/entity-migrator
codraw/doctrine-extra
codraw/aws-tool-kit
codraw/validator
codraw/workflow
codraw/open-api
codraw/cron-job
codraw/process
codraw/log
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony