milebits / eloquent-draftable
为你的 eloquent 模型添加可草拟的功能。
1.0.3
2022-02-10 14:24 UTC
Requires
- illuminate/support: ^8|^9
- milebits/helpers: ^3.0
Requires (Dev)
README
为你的 eloquent 模型添加可草拟的功能。
安装
您可以通过 composer 安装此包。
composer require milebits/eloquent-draftable
设置
-
将可空的时间戳列
published_at
添加到你的模型数据库表中。$table->timestamp('published_at')->nullable();
-
在你的模型中包含
Optix\Draftable\Draftable
特性。class Post extends Model { use Draftable; }
更改默认的 published_at
列名
use Milebits\EloquentDraftable\Draftable; class Post extends Model { use Draftable; const PUBLISHED_AT_COLUMN = 'your_custom_column'; }
然后在你的迁移中,用任何你想要的名称来更改它。
用法
查询作用域
当在模型中包含 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 = now()->addWeek(); // $publishDate = '2020-01-01 00:00:00'; // $publishDate = '+1 week'; // Schedule without saving... $post->setPublishedAt($publishDate); // Schedule and save... $post->publishAt($publishDate);
上述方法都需要一个类型为 Illuminate\Support\Carbon|string|null
的 $date
参数。
获取模型的发布状态
// Determine if the model is published... $post->isPublished(); // Determine if the model is draft... $post->isDraft();
许可证
此包采用 Apache 许可证 2.0 许可。