doloan09/laravel-model-expires

一个为 Eloquent 模型分配过期日期的包

1.0 2023-04-28 07:55 UTC

This package is auto-updated.

Last update: 2024-09-28 11:12:07 UTC


README

Laravel Model Expires

PHP version Latest Version on Packagist Software License Tests Code style Total Downloads

为 Eloquent 模型分配过期日期

安装

您可以通过 composer 安装此包

composer require mvdnbrk/laravel-model-expires

使用方法

要在模型上使用过期日期,请使用 Expirable 特性

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Mvdnbrk\EloquentExpirable\Expirable;

class Subscription extends Model
{
    use Expirable;
}

您应该在数据库表中添加一个 expires_at 列。
此包包含一个辅助方法来创建此列

class CreateSubscriptionsTable extends Migration
{
    public function up(): void
    {
        Schema::create('subscriptions', function (Blueprint $table) {
            $table->expires();
        });
    }

    public function down(): void
    {
        Schema::dropExpires();
    }
}

Expirable 特性会自动将 expires_at 属性转换为 DateTime / Carbon 实例。

自定义列名

您可以通过设置 EXIRES_AT 常量或通过在您的模型上重写 getExpiresAtColumn 方法来自定义列名。

class Subscription extends Model
{
    use Expirable;

    const EXPIRES_AT = 'ends_at';
}
$table->expires('ends_at');
$table->dropExpires('ends_at');

设置过期时间

您可以通过设置 expires_at 属性并指定秒数 TTL 来设置模型的过期时间

$subscription->expires_at = 600;

您也可以传递一个表示过期日期的 DateTime 实例,而不是传递秒数的整数

$subscription->expires_at = now()->addMinutes(10);

取消过期

您可以通过设置负数或零 TTL 或使用 discardExpiration 方法来取消模型的过期

$subscription->expires_at = 0;
$subscription->expires_at = -5;

$subscription->discardExpiration()->save();

确定过期时间

要确定给定的模型实例是否已过期,请使用 expired 方法

if ($subscription->expired()) {
    //
}

要确定给定的模型将在未来过期,请使用 willExpire 方法

if ($subscription->willExpire()) {
    //
}

查询模型

withoutExpired 方法将检索未过期的模型

$subscriptions = App\Models\Subscription::withoutExpired()->get();

onlyExpired 方法将仅检索已过期的模型

$subscriptions = App\Models\Subscription::onlyExpired()->get();

expiring 方法将仅检索将过期在未来的模型

$subscriptions = App\Models\Subscription::expiring()->get();

notExpiring 方法将仅检索将不会过期的模型

$subscriptions = App\Models\Subscription::notExpiring()->get();

待办事项

  • 添加一个 expired:prune 控制台命令来删除过期的模型,或执行自定义实现。
  • 添加一个查询作用域,以查询将在 ... 过期的模型

测试

composer test

变更日志

请参阅 CHANGELOG 以获取有关最近更改的更多信息。

贡献

请参阅 CONTRIBUTING 以获取详细信息。

安全漏洞

请审查 我们的安全策略 以了解如何报告安全漏洞。

致谢

许可证

MIT 许可证 (MIT)。有关更多信息,请参阅 许可证文件