$ composer require amrnrd/likeable
This step is optional
$ php artisan vendor:publish --provider="AmrNRD\\Likeable\\LikeServiceProvider" --tag=config
This step is also optional, if you want to custom likes table, you can publish the migration files:
$ php artisan vendor:publish --provider="AmrNRD\\Likeable\\LikeServiceProvider" --tag=migrations
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use AmrNRD\Likeable\Traits\Liker;
class User extends Authenticatable
{
use Liker;
<...>
}
use Illuminate\Database\Eloquent\Model;
use AmrNRD\Likeable\Traits\Likeable;
class Post extends Model
{
use Likeable;
<...>
}
$user = User::find(1);
$post = Post::find(2);
$user->like($post);
$user->dislike($post);
$user->doLike($post);
$user->doesnotLike($post);
$post->isLikedBy($user);
Get user likes with pagination:
$likes = $user->likes()->with('likeable')->paginate(20);
foreach ($likes as $like) {
$like->likeable; // App\Post instance
}
Get object likers:
foreach($post->likers as $user) {
// echo $user->name;
}
with pagination:
$likers = $post->likers()->paginate(20);
foreach($likers as $user) {
// echo $user->name;
}
// all
$user->likes()->count();
// with type
$user->likes()->withType(Post::class)->count();
// likers count
$post->likers()->count();