ufutx / laravel-favorite
允许 Laravel Eloquent 模型实现“收藏”、“记住”或“关注”功能。
Requires
- php: >=5.5.9
- illuminate/database: >=5.0
- illuminate/support: >=5.2
Requires (Dev)
- orchestra/database: ~3.0
- orchestra/testbench: ~3.0
- phpunit/phpunit: ~4.0
This package is not auto-updated.
Last update: 2024-09-28 19:26:07 UTC
README
允许 Laravel Eloquent 模型实现“收藏”、“记住”或“关注”功能。
索引
安装
- 通过 Composer 安装此包
$ composer require ufutx/laravel-favorite
- 通过在
config/app.php中添加服务提供者条目来更新config/app.php。
'providers' => [ // ... Ufutx\LaravelFavorite\FavoriteServiceProvider::class, ];
- 从命令行迁移数据库
php artisan migrate
模型
您的用户模型应该导入 Traits/Favoriteability.php 特性并使用它,该特性允许用户收藏模型。(下面是一个示例)
use Ufutx\LaravelFavorite\Traits\Favoriteability; class User extends Authenticatable { use Favoriteability; }
您的模型应该导入 Traits/Favoriteable.php 特性并使用它,该特性包含您将用于允许模型可收藏的方法。在所有示例中,我将使用 Post 模型作为可收藏的模型,例如只是提案。(下面是一个示例)
use Ufutx\LaravelFavorite\Traits\Favoriteable; class Post extends Model { use Favoriteable; }
就是这样...您的模型现在 “可收藏”!现在用户可以收藏具有可收藏特性的模型。
用法
模型可以带或不带认证用户进行收藏(下面是示例)
添加到收藏和从收藏中移除
如果 favorite 方法中没有传递参数,则模型将假定当前认证用户。
$post = Post::find(1); $post->addFavorite(); // auth user added to favorites this post $post->removeFavorite(); // auth user removed from favorites this post $post->toggleFavorite(); // auth user toggles the favorite status from this post
如果 favorite 方法中传递了参数,则模型将假定具有该 ID 的用户。
$post = Post::find(1); $post->addFavorite(5); // user with that id added to favorites this post $post->removeFavorite(5); // user with that id removed from favorites this post $post->toggleFavorite(5); // user with that id toggles the favorite status from this post
用户模型也可以添加到收藏和从收藏中移除
$user = User::first(); $post = Post::first(); $user->addFavorite($post); // The user added to favorites this post $user->removeFavorite($post); // The user removed from favorites this post $user->toggleFavorite($post); // The user toggles the favorite status from this post
返回用户的收藏对象
用户可以返回他标记为收藏的对象。您只需要在 User 模型中将 class 作为 favorite() 方法的参数传递。
$user = Auth::user(); $user->favorite(Post::class); // returns a collection with the Posts the User marked as favorite
从一个对象返回收藏计数
您可以从一个对象返回收藏计数,只需从模型中返回 favoritesCount 属性。
$post = Post::find(1); $post->favoritesCount; // returns the number of users that have marked as favorite this object.
返回标记此对象为收藏的用户
您可以通过调用对象中的 favoritedBy() 方法返回标记此对象的用户。
$post = Post::find(1); $post->favoritedBy(); // returns a collection with the Users that marked the post as favorite.
测试
此包已集成测试,所以每次您提交拉取请求时,您的代码都将被测试。
变更日志
请参阅 CHANGELOG 获取有关最近更改的更多信息。
贡献
欢迎贡献并会得到充分认可。我们通过 Github 上的拉取请求接受贡献。
拉取请求
-
PSR-2 编码标准 - 使用
$ composer check-style检查代码风格,并使用$ composer fix-style修复它。 -
添加测试! - 如果您的补丁没有测试,则不会被接受。
-
记录任何行为更改 - 确保更新
README.md和任何其他相关文档。 -
考虑我们的发布周期 - 我们尝试遵循 SemVer v2.0.0。随机破坏公共 API 不是一种选择。
-
创建功能分支 - 不要要求我们从您的 master 分支中提取。
-
每个功能一个拉取请求 - 如果您想做更多的事情,请发送多个拉取请求。
-
发送连贯的历史记录 - 确保您的拉取请求中的每个单独提交都很有意义。如果您在开发过程中必须进行多个中间提交,请在提交之前请压缩它们。
安全
请在问题页面上报告您发现的问题。
欢迎拉取请求。
致谢
许可证
MIT 许可协议 (MIT)。更多信息请参阅许可文件。