Package Data | |
---|---|
Maintainer Username: | bmatovu |
Maintainer Contact: | mtvbrianking@gmail.com (Brian Matovu) |
Package Create Date: | 2020-06-22 |
Package Last Update: | 2020-12-13 |
Language: | PHP |
License: | MIT |
Last Refreshed: | 2024-12-23 03:24:32 |
Package Statistics | |
---|---|
Total Downloads: | 36 |
Monthly Downloads: | 0 |
Daily Downloads: | 0 |
Total Stars: | 3 |
Total Watchers: | 1 |
Total Forks: | 1 |
Total Open Issues: | 3 |
This package contains a trait to make Eloquent models publishable. It enables the model to hold a published vs non-published state, which comes in handy for things like blog posts that can be drafts or final (published) posts.
It uses a published_at
attribute to determine the model state ie, if the model published_at is null, the model isn't published.
Install via Composer package manager:
composer require bmatovu/laravel-publishable
You should also add the publsihed_at
column to your database table.
<?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();
});
}
}
To make a model publishable, use the Bmatovu\Publishable\Publishable
trait on the model:
<?php
namespace App;
use Bmatovu\Publishable\Publishable;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use Publishable;
}
{tip} The
Publishable
trait will automatically cast thepublished_at
attribute to aDateTime
/Carbon
instance for you.
Now, when you call the publish
method on the model, the published_at
column will be set to the current date and time. And, when querying a model that is publishable, the unpublished models will automatically be excluded from all query results.
To determine if a given model instance has been published, use the isPublished
method:
if ($post->isPublished()) {
//
}
Unpublished models are automatically be excluded from query results.
$publishedPosts = Post::get();
$publishedPosts = Post::onlyPublished()->get();
However, you may force unpublished models to appear in a result set using the withDrafts
method on the query:
$posts = Posts::withDrafts()->get();
You may also retrieve only unpublished models using the onlyDrafts
method.
$drafts = Posts::onlyDrafts()->get();
Sometimes you may need to save a model as published in your database. For this, use the publish
method:
// Publishing a single model instance...
$post->publish();
// Publishing all related models...
$post->inLifeStyle()->publish();
Sometimes you may wish to "un-published" a published model. To toogle a published model into an inactive state, use the unpublish
method on a model instance:
$post->unpublish();