optix/eloquent-draftable

为您的 eloquent 模型添加可草稿功能。

v2.1.0 2020-10-13 09:55 UTC

This package is auto-updated.

Last update: 2024-09-13 18:37:30 UTC


README

Packagist Version GitHub Workflow Status StyleCI

为您的 eloquent 模型添加可草稿功能。

安装

您可以通过 composer 安装此包。

composer require optix/eloquent-draftable

配置

  1. 将可空的时间戳列 published_at 添加到您的模型数据库表中。

    $table->timestamp('published_at')->nullable();
  2. 在您的模型中包含 Optix\Draftable\Draftable 特性。

    class Post extends Model
    {
        use Draftable;
    }

用法

查询作用域

当在模型中包含 Draftable 特性时,将注册一个全局作用域,以自动排除查询结果中的草稿记录。因此,要查询草稿记录,您必须应用以下概述的本地作用域之一。

// Only retrieve published records...
$onlyPublished = Post::all();

// Retrieve draft & published records...
$withDrafts = Post::withDrafts()->get();

// Only retrieve draft records...
$onlyDrafts = Post::onlyDrafts()->get();

发布模型

$post = Post::withDrafts()->first();

// Publish without saving...
$post->setPublished(true);

// Publish and save...
$post->publish(); // or $post->publish(true);

当您尝试发布已经发布的模型时,published_at 时间戳将不会被更新。

草稿模型

// Draft without saving...
$post->setPublished(false);

// Draft and save...
$post->draft(); // or $post->publish(false);

安排模型发布

$publishDate = Carbon::now()->addWeek();
// $publishDate = '2020-01-01 00:00:00';
// $publishDate = '+1 week';

// Schedule without saving...
$post->setPublishedAt($publishDate);

// Schedule and save...
$post->publishAt($publishDate);

上述方法都要求有一个类型为 DateTimeInterface|string|null$date 参数。

获取模型的发布状态

// Determine if the model is published...
$post->isPublished();

// Determine if the model is draft...
$post->isDraft();

许可证

此包根据 MIT 许可证 许可。