Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Eloquent Publishing Laravel Package

lemaur/eloquent-publishing

Add publishing support to Laravel Eloquent models with a simple trait. Manage publish dates, query scopes and helpers, plus custom migration blueprint methods to quickly add publishing columns and build publishable content workflows.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package (requires Laravel 11+ and PHP 8.2+):
    composer require lemaur/eloquent-publishing
    
  2. Add the Publishes trait to your Eloquent model:
    use Lemaur\Publishing\Database\Eloquent\Publishes;
    
    class Post extends Model
    {
        use Publishes;
    }
    
  3. Add the published_at column to your migration using the provided blueprint method:
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->publishes(); // Adds nullable timestamp `published_at`
    });
    

First Use Case

Publish a model instance in a controller:

$post = Post::find(1);
$post->publish(); // Sets `published_at` to current timestamp

Implementation Patterns

Core Workflows

  1. Model Lifecycle Management:

    // Publish with custom date (e.g., scheduled content)
    $post->publish(Carbon::parse('2025-12-31'));
    
    // Unpublish
    $post->unpublish();
    
    // Check status
    if ($post->isPublished()) { ... }
    if ($post->isPlanned()) { ... }
    
  2. Query Scoping:

    // Filter published content
    $published = Post::onlyPublished()->get();
    
    // Filter scheduled content
    $scheduled = Post::onlyPlanned()->get();
    
    // Combine filters
    $active = Post::onlyPlannedAndPublished()->get();
    
  3. Ordering:

    // Latest published first
    $recent = Post::onlyPublished()->latestPublished()->get();
    
    // Oldest scheduled first
    $oldest = Post::onlyPlanned()->oldestPlanned()->get();
    

Integration Tips

  • Events: Listen for publishing, published, unpublishing, or unpublished events to trigger side effects (e.g., notifications, cache updates).

    Post::published(function ($post) {
        // Send email when published
    });
    
  • Custom Column Names: Override the default published_at column:

    class Post extends Model
    {
        use Publishes;
    
        const PUBLISHED_AT = 'release_date';
    }
    

    Update migrations to match:

    $table->publishes('release_date');
    
  • Timezone Support: Use publishesTz() for timezone-aware timestamps (requires Laravel 11+ and PHP 8.2+).

Common Use Cases

  1. Scheduled Content:
    $post->publish(Carbon::tomorrow()); // Future publishing
    
  2. Draft Management:
    if ($post->isNotPublished()) { ... }
    
  3. Content Rotations:
    $featured = Post::onlyPublished()->latestPublished()->take(3)->get();
    

Gotchas and Tips

Pitfalls

  1. Laravel/PHP Version Requirement:

    • Breaking Change: This release drops support for Laravel 10 and PHP 8.1. Ensure your project uses Laravel 11+ and PHP 8.2+.
    • Fix: Update your project dependencies if not already compliant.
  2. Column Mismatch:

    • If PUBLISHED_AT is defined in the model but the migration uses a different column name, queries will fail.
    • Fix: Ensure consistency between model constant and migration.
  3. Null Handling:

    • isPublished() returns false for null values (unpublished). Use isPlanned() for future dates.
  4. Event Timing:

    • publishing/unpublishing events fire before the timestamp is set. Use published/unpublished for post-update logic.

Debugging

  • Missing Column: Run php artisan migrate:fresh if the published_at column is missing.
  • Query Issues: Verify scope methods (e.g., onlyPublished()) by inspecting the generated SQL with ->toSql().
  • Version Mismatch: If using older Laravel/PHP versions, downgrade to 3.x:
    composer require lemaur/eloquent-publishing:^3.3
    

Extension Points

  1. Custom Logic: Override trait methods (e.g., publish()) to add validation or business rules:

    public function publish($date = null)
    {
        if (!$this->isApproved()) {
            throw new \Exception('Content must be approved first.');
        }
        $this->published_at = $date ?? now();
        $this->save();
    }
    
  2. Global Scopes: Extend the trait to add default query scopes:

    use Lemaur\Publishing\Database\Eloquent\Publishes;
    
    class Post extends Model
    {
        use Publishes;
    
        protected static function booted()
        {
            static::addGlobalScope(new PublishedScope());
        }
    }
    
  3. Testing: Mock the published_at attribute for tests:

    $post = Post::factory()->create(['published_at' => now()->addDay()]);
    $this->assertTrue($post->isPlanned());
    

Performance

  • Indexing: Add an index to published_at for large datasets:
    $table->publishes();
    $table->index('published_at');
    
  • Eager Loading: Avoid N+1 queries when checking publication status:
    $posts = Post::with('author')->onlyPublished()->get();
    

Configuration Quirks

  • Timezone Awareness: Use publishesTz() for timezone-aware timestamps, but ensure your database supports it (e.g., PostgreSQL).
  • Precision: The publishes() method accepts a precision parameter (default: 0), which may affect storage for microsecond-level timestamps.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle