A modern, flexible, and test-covered Laravel package that allows your models to handle reaction functionality (like, dislike, love, etc.). This package provides a clean API for both reactable (e.g., articles, posts) and reactor (e.g., users, devices) models.
Install via composer:
composer require jobmetric/laravel-reaction
Then publish and run the migration:
php artisan migrate
use JobMetric\Reaction\HasReaction; class Article extends Model { use HasReaction; }
use JobMetric\Reaction\CanReact; class User extends Model { use CanReact; }
$article->addReaction('like', $user); // with user $article->addReaction('like', null, ['device_id' => 'abc123']); // anonymous
$article->toggleReaction('like', $user); // Adds if not exists, removes if exists
$article->removeReaction('like', $user);
$article->removeAllReactions($user); // or pass device_id
$article->updateReaction('like', 'dislike', $user);
$article->restoreReaction('like', $user);
$article->totalReactions();
$article->countReactions('like');
$article->reactionSummary(); // returns: ['like' => 3, 'dislike' => 1]
$article->hasReaction('like', $user);
$article->latestReactions(5);
$article->reactionTo($user);
$user->hasReactedTo($article);
$user->reactedWithTo('like', $article);
$user->reactionSummary(); // ['like' => 3, 'dislike' => 2]
$user->reactedItems(); // Returns models $user->reactedItems('like', Article::class);
$user->latestReactionsGiven(10);
Field | Description |
---|---|
reactor_type | Polymorphic class of reactor (e.g., User) |
reactor_id | ID of the reactor |
reactable_type | Polymorphic class of reactable (e.g., Post) |
reactable_id | ID of the reactable |
reaction | Reaction type (e.g., like, love, etc.) |
ip | IP address of reaction |
device_id | Optional device identifier |
source | Source (e.g., web, app, api) |
Event | Triggered When |
---|---|
ReactionAddEvent | A new reaction is added |
ReactionRemovingEvent | Before a reaction is removed |
ReactionRemovedEvent | After a reaction is removed |
This package uses SoftDeletes and supports automatic pruning:
php artisan model:prune
You can configure the number of days in your config:
'reaction' => [ 'prune_days' => 30, ],
Thank you for considering contributing to the Laravel Reaction! The contribution guide can be found in the CONTRIBUTING.md.
This package is open-sourced under the MIT license.