编程

使用 Laravel Ban 包禁用 Eloquent 模型

Martin Hwang 594 2021-12-05 22:55:05

Laravel Bans 是一个用于禁用 Eloquent 模型的包。使用该包,你可以迅速让一个模型"bannable".

用例可以超越用户模型; 你可以将 ban 的概念用到任何 Eloquent 模型中。 主要特性包括:

  • 一个模型可以有多个
  • 删掉的bans以软删除的方式保存在历史记录里。
  • 大部分逻辑由BanService处理。
  • 有中间件保护被禁用的用户路由权限。
  • 用例不限于用户模型,任何 Eloquent 模型都可以被禁用。
  • 模型 ban 及 unban 的事件触发
  • 用于与 Laravel Eloquent 模型的配合使用
  • 有 Laravel Nova 支持.
  • 使用 contract 使之保持高定制能力
  • 使用 trait, 使功能开箱即用

优雅的 API 使禁用模型易用:

 $user->ban();
  
 $user->ban([
     'comment' => 'Enjoy your ban!',
 ]);
  
 // A ban that has a ban expiry date
 $user->ban([
     'expired_at' => '+1 month',
]);

 // Remove a ban
$user->unban();

// Boolean checks
$user->isBanned();
$user->isNotBanned();
$ban->isTemporary();

The package also provides nice conveniences like middleware, events, scopes, and auto-applying scopes to a model.

You can learn more about this package, get full installation instructions, and view the source code on GitHub.