Managing a blog platform can be overwhelming, especially when you need to publish posts at the right time. Luckily, Laravel provides powerful tools for automation. In this post, Iβll walk you through how I built an auto-publishing blog system using Laravel's Task Scheduler and cron jobs.
π οΈ What I Built
A feature where:
Blog posts are scheduled with a publish_date.
Posts are automatically published when their publish_date is reached.
No manual intervention is needed.
Scheduled command runs every minute using cron.
π§© Database Setup
In the blogs table, I added two important fields:
$table->boolean('publish')->default(0); // 0 = draft, 1 = published, 2 = scheduled
$table->timestamp('publish_date')->nullable(); // schedule time
publish = 2 means the blog is scheduled.
publish = 1 means it's visible/public.
π§ Creating the Artisan Command
I created a custom command to auto-publish blogs:
php artisan make:command AutoPublishBlogs
Inside App\Console\Commands\AutoPublishBlogs.php:
public function handle()
{
$now = \Carbon\Carbon::now();
$blogs = \App\Models\Blog::where('publish', 2)
->where('publish_date', '<=', $now)
->update(['publish' => 1]);
$this->info("{$blogs} blog(s) auto-published.");
\Log::info("Auto-published {$blogs} blog(s) at " . now());
return 0;
}
π§° Registering the Command
Inside App\Console\Kernel.php:
protected $commands = [
\App\Console\Commands\AutoPublishBlogs::class,
];
And in the schedule() method:
protected function schedule(Schedule $schedule)
{
$schedule->command('blogs:auto-publish')->everyMinute();
}
π°οΈ Setting Up the Cron Job
To make Laravel's scheduler work, I set up a cron job to call Laravelβs scheduler every minute.
crontab -e
Then I added this line (update path as per your Laravel project):
* * * * * cd /home/bio/development/topasia/topasia-new && php artisan schedule:run >> /dev/null 2>&1
This runs Laravelβs scheduler every minute, which in turn checks for scheduled blogs to publish.
β
Testing It All
I tested it by:
Creating a blog post with publish = 2.
Setting the publish_date a few minutes in the future.
Watching it auto-publish as the minute changed (thanks to the scheduler!).
You can also manually trigger the scheduler with:
php artisan schedule:run
π‘ Bonus: Showing Only Published Blogs
In various frontend queries, I updated blog fetching logic to show only published ones:
Blog::where('publish', 1)->orderBy('publish_date', 'desc')->paginate(12);
Top comments (0)