bmatovu / laravel-publishable
Laravel 发布功能。
v1.1.0
2020-12-10 17:39 UTC
Requires
- php: >=7.0.0
- illuminate/database: ^5.5|^6.0|^7.0|^8.0
Requires (Dev)
- fzaninotto/faker: ~1.4
- illuminate/queue: ^5.5|^6.0|^7.0|^8.0
- illuminate/support: ^5.5|^6.0|^7.0|^8.0
- orchestra/testbench: ^3.5|^4.0|^5.0|^6.0
- phpunit/phpunit: ^6.0|^7.0|^8.0|^9.0
This package is auto-updated.
Last update: 2024-09-14 01:25:31 UTC
README
此包包含一个特性,可以使 Eloquent 模型具有发布功能。它使模型能够保留发布和非发布状态,这对于像博客文章这样的草稿或最终(发布)文章很有用。
它使用一个 published_at
属性来确定模型状态,即如果模型的 published_at 为空,则模型未发布。
安装
通过 Composer 软件包管理器安装
composer require bmatovu/laravel-publishable
用法
将 published_at
列添加到您的数据库表中。
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePostsTable extends Migration { public function up() { Schema::create('posts', function (Blueprint $table) { // ... $table->timestamp('published_at')->nullable(); }); } }
要使模型具有发布功能,请在模型上使用 Bmatovu\Publishable\Publishable
特性
<?php namespace App\Models; use Bmatovu\Publishable\Publishable; use Illuminate\Database\Eloquent\Model; class Post extends Model { use Publishable; }
{提示}
Publishable
特性会自动将published_at
属性转换为DateTime
/Carbon
实例。
现在,当您在模型上调用 publish
方法时,published_at
列将被设置为当前日期和时间。
查询发布功能模型
当查询一个具有发布功能的模型时,未发布的模型将自动从所有查询结果中排除。
$publishedPosts = Post::get(); $publishedPosts = Post::onlyPublished()->get();
但是,您可以使用查询上的 withDrafts
方法强制未发布的模型出现在结果集中。
$posts = Posts::withDrafts()->get();
您也可以使用 onlyDrafts
方法仅检索未发布的模型。
$drafts = Posts::onlyDrafts()->get();
要确定给定的模型实例是否已发布,请使用 isPublished
方法
if ($post->isPublished()) { // ... }
发布模型
您可以将模型保存为已发布状态,如下所示;
// Publishing a single model instance... $post->publish(); // Publishing all related models... $post->inLifeStyle()->publish();
取消发布模型
您可以将已发布的模型“取消发布”,如下所示;
$post->unpublish();