hayrullah / laravel-likes
这个库改进了记录请求点赞并统计所有已点赞链接的功能。
v1.0
2020-05-19 03:54 UTC
Requires
- php: >=7.1.0
- laravel/framework: ^5.5|^6.0|^7.0
This package is auto-updated.
Last update: 2024-09-19 04:37:01 UTC
README
文档、安装和使用说明
请参阅文档以获取详细的安装和使用说明。
安装
$ composer require hayrullah/laravel-likes
- 在 Laravel >=5.5 中,此包将自动注册。对于旧版本,请通过在
config/app.php
中添加服务提供者条目来更新它。
'providers' => [ // ... Hayrullah\Likes\LikeServiceProvider::class, ];
- 从命令行发布数据库
php artisan vendor:publish --provider="Hayrullah\Likes\LikeServiceProvider"
- 从命令行迁移数据库
php artisan migrate
模型
您的用户模型应导入 Traits/Likability.php
特性并使用它,该特性允许用户对模型进行点赞。(见下面的示例)
use Hayrullah\Likes\Traits\Likability; class User extends Authenticatable { use Likability; }
您的模型应导入 Traits/Likable.php
特性并使用它,该特性包含您将用于允许模型可点赞的方法。在我所有的示例中,我将使用 Article 模型作为可点赞的模型,这是为了示例目的。
- 见下面的示例
use Hayrullah\Likes\Traits\Likable; class Article extends Model { use Likable; }
就是这样...您的模型现在已变为 "可点赞"!现在用户可以对具有可点赞特性的模型进行点赞。
用法
模型可以带或不带认证用户进行点赞(见下面的示例)
添加到点赞和从点赞中移除
如果点赞方法中没有传递参数,则模型将假定认证用户。
$article = Article::first(); $article->addLike(); // auth user added to likes this article $article->removeLike(); // auth user removed from likes this article $article->toggleLike(); // auth user toggles the like status from this article
如果点赞方法中传递了参数,则模型将假定具有该 ID 的用户。
$article = Article::first(); $article->addLike(5); // user with that id added to likes this article $article->removeLike(5); // user with that id removed from likes this article $article->toggleLike(5); // user with that id toggles the like status from this article
用户模型也可以添加到点赞和从收藏中移除
$user = User::first(); $article = Article::first(); $user->addLike($article); // The user added to likes this article $user->removeLike($article); // The user removed from likes this article $user->toggleLike($article); // The user toggles the like status from this article
返回用户的点赞对象
用户可以返回他标记为点赞的对象。您只需在 User
模型的 like()
方法中传递 类。
$user = Auth::user(); $user->like(Article::class); // returns a collection with the Articles the User marked as like
从对象返回点赞数
您可以从对象返回点赞数,只需从模型返回 likesCount
属性即可。
$article = Article::first(); $article->likesCount; // returns the number of users that have marked as like this object.
返回标记此对象为点赞的用户
您可以通过在对象中调用 likedBy()
方法来返回标记此对象的用户。
$article = Article::first(); $article->likedBy(); // returns a collection with the Users that marked the article as like.
检查用户是否已经点赞对象
您可以通过在对象中调用 isLiked()
方法来检查认证用户是否已经点赞了对象。
$article = Article::first(); $article->isLiked(); // returns a boolean with true or false.
测试
该包集成了测试,因此每次您提交拉取请求时,您的代码都会被测试。
变更日志
有关最近更改的更多信息,请参阅 变更日志。