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

Laravel Reactions Laravel Package

binafy/laravel-reactions

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require binafy/laravel-reactions
    

    Publish the migration and config:

    php artisan vendor:publish --provider="Binafy\Reactions\ReactionsServiceProvider" --tag="migrations"
    php artisan vendor:publish --provider="Binafy\Reactions\ReactionsServiceProvider" --tag="config"
    

    Run the migration:

    php artisan migrate
    
  2. Configure Reactions: Edit config/reactions.php to define your emoji types (e.g., like, love, laugh):

    'types' => [
        'like' => ['emoji' => 'πŸ‘', 'name' => 'Like'],
        'love' => ['emoji' => '❀️', 'name' => 'Love'],
        'laugh' => ['emoji' => 'πŸ˜‚', 'name' => 'Laugh'],
    ],
    
  3. First Use Case: Add reactions to a model (e.g., Post):

    use Binafy\Reactions\HasReactions;
    
    class Post extends Model
    {
        use HasReactions;
    }
    

    React to a post in a controller:

    $post = Post::find(1);
    $post->react('like'); // User automatically reacts (via middleware)
    

Implementation Patterns

Core Workflows

  1. Reacting to Models:

    // Add a reaction
    $model->react('like');
    
    // Remove a reaction
    $model->unreact('like');
    
    // Toggle reaction
    $model->toggleReaction('like');
    
  2. Fetching Reactions:

    // Get all reactions for a model
    $reactions = $model->reactions;
    
    // Get reaction count by type
    $count = $model->reactionCount('like');
    
    // Get users who reacted
    $users = $model->reactedUsers('like');
    
  3. Middleware for Automatic Reactions: Use Binafy\Reactions\Middleware\React to auto-react based on user actions:

    // In routes/web.php
    Route::middleware(['auth', 'react'])->group(function () {
        // Routes where reactions are auto-applied
    });
    
  4. Customizing Reaction Logic: Override default behavior via traits or service providers:

    // In AppServiceProvider
    Reactions::extend('custom', function ($model, $type) {
        // Custom logic for 'custom' reaction type
    });
    
  5. API Integration:

    // React via API
    $response = $model->react('like', request()->user());
    return response()->json($response);
    

Gotchas and Tips

Pitfalls

  1. Middleware Timing:

    • The React middleware runs after the route handler. Ensure your logic accounts for this (e.g., avoid reacting to a model before it’s saved).
    • Example: If reacting in a store method, move the reaction logic to a created observer or use Reactions::react($model, 'like') manually.
  2. Duplicate Reactions:

    • By default, users can only react once per type. To allow multiple reactions, override the canReact method in your model:
      public function canReact($type)
      {
          return true; // Always allow
      }
      
  3. Performance:

    • Reaction counts are cached by default. Clear the cache if counts appear stale:
      php artisan cache:clear
      
    • For high-traffic models, consider denormalizing reaction counts into the model itself (e.g., likes_count column).
  4. Config Overrides:

    • The config/reactions.php file is published but not merged. Ensure you copy all required keys (e.g., types, table_name) to avoid runtime errors.
  5. Testing:

    • Mock the React middleware in tests:
      $this->actingAs($user)->withMiddleware(\Binafy\Reactions\Middleware\React::class);
      

Tips

  1. Dynamic Emoji Types: Add reaction types dynamically via the config or a service provider:

    Reactions::addType('custom', ['emoji' => 'πŸŽ‰', 'name' => 'Celebrate']);
    
  2. Reaction Events: Listen for reaction events to trigger side effects:

    // In EventServiceProvider
    protected $listen = [
        \Binafy\Reactions\Events\ReactionAdded::class => [
            \App\Listeners\NotifyAuthor::class,
        ],
    ];
    
  3. Batch Processing: Use Reactions::sync() to bulk-update reactions (e.g., for imports):

    Reactions::sync($model, ['like', 'love']); // Sync to these types only
    
  4. Localization: Localize emoji names in config/reactions.php:

    'types' => [
        'like' => [
            'emoji' => 'πŸ‘',
            'name' => trans('reactions.like'),
        ],
    ],
    
  5. Debugging:

    • Check the reactions table for orphaned entries if counts are incorrect.
    • Use Reactions::debug() to log reaction activity (enable in config):
      'debug' => env('REACTIONS_DEBUG', false),
      
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui