Models & traits
Add the HasLikes trait to models that can be liked and the GivesLikes trait to models that give likes. Any Eloquent model can play either role — users, teams, organisations:
use Illuminate\Database\Eloquent\Model;
use RoundlyConsulting\Likes\Traits\GivesLikes;
use RoundlyConsulting\Likes\Traits\HasLikes;
class Post extends Model
{
use HasLikes; // can be liked
}
class User extends Model
{
use GivesLikes; // can give likes
}What each trait adds
- HasLikes — likes() received, isLikedBy() / hasBeenLikedBy(), likesCount(), reactionSummary(), toLikeArray() and the query scopes (withLikesCount, orderByLikes, whereLikedBy, withLikedState, orderByLikeScore, orderByTrending …).
- GivesLikes — likes() given, like(), unlike(), toggleLike(), react() / switchReaction(), likeMany() / unlikeMany(), hasLiked(), likedItems() and likesOf().
The verbs and reads on both traits are sugar over the same manager as the Likes facade, so Likes::fake() records them too:
$user->like($post); // = Likes::actor($user)->like($post)
$post->likesCount(); // = Likes::for($post)->count()
$post->reactionSummary(); // = Likes::for($post)->summary()Relations
Both traits add a likes() MorphMany relation — the likes a model received on a likeable, the likes it gave on an actor:
$post->likes; // Collection<Like> — likes the post received
$user->likes; // Collection<Like> — likes the user gave
$post->likes()->where('type', 'love')->count(); // a plain MorphMany — query it freely
$user->likes()->latest()->limit(5)->get();Because both traits define likes(), PHP reports a trait collision if one model uses both.
The Likeable contract
HasLikes implements every method of RoundlyConsulting\Likes\Contracts\Likeable — isLikedBy(), likesCount(), reactionSummary() and toLikeArray(). Declare the interface when you want to type-hint against likeable models:
use Illuminate\Database\Eloquent\Model;
use RoundlyConsulting\Likes\Contracts\Likeable;
use RoundlyConsulting\Likes\Traits\HasLikes;
class Comment extends Model implements Likeable
{
use HasLikes;
}The Like model
Each row is a RoundlyConsulting\Likes\Models\Like — a soft-deleting Eloquent model with actor() and likeable() morph-to relations and a factory (see Testing):
$like = $post->likes()->latest()->first();
$like->actor; // the model that gave the like (MorphTo)
$like->likeable; // the model that received it (MorphTo)
$like->type; // 'like', 'love', ...
$like->created_at; // when it was givenShow your open-source love
This package is free and MIT-licensed. If it saves you time, a one-off donation or a Patreon membership keeps it maintained, tested and documented.
More ways to support, including cryptoBy donating, you agree to our donation terms.
Want this built into your product?
We integrate our packages into custom Laravel and AI builds. Tell us what you're working on and we'll reply within 48 hours.