Reputation: 63
I added spatie/laravel-sitemap to my Laravel app and it is working when i run the command php artisan sitemap:generate, but I can't figure it out how to make it work automatically with Kernel.php schedule.
I added $schedule->command('sitemap:generate')->hourly(); but it is not working
Console/Commands/GenerateSitemap.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Spatie\Sitemap\SitemapGenerator;
class GenerateSitemap extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $signature = 'sitemap:generate';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate the sitemap.';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// modify this to your own needs
SitemapGenerator::create('mywebsite')
->writeToFile(public_path('sitemap.xml'));
}
}
Console\Kernel.php
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
Commands\GenerateSitemap::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('sitemap:generate')->hourly();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
What should I add to make it generate automatically the sitemap every hour?
Upvotes: 2
Views: 1527
Reputation: 13
Question is pretty old, but as answer was not provided- let me add info, just in case it will help someone (as some other "years after" responses have helped me at the beginning of my IT path)
Console/Commands/GenerateSitemap.php
is absolutely fine
Console\Kernel.php
is also absolutely fine
Including for latest Laravel (on moment of answer v11)
Your problem is that you have not defined cron. Here is Laravel documentation: https://laravel.com/docs/11.x/scheduling#running-the-scheduler
And here is my instruction (assuming that you have server access):
sudo crontab -u www-data -e
(executing crontab
editor as www-data user, as it is most common to run web-server under this user, but in case of something replace it with your user);* * * * * cd /var/www/your-project-dir && php artisan schedule:run >> /dev/null 2>&1
(replacing your-project-dir with the name of your projects directory);:x
if you are in vim);hourly()
it will be executed at XX:00 and so on;Upvotes: 1
Reputation: 1
You should declare in projected commands like this \App\Console\Commands\GenerateSitemap::class
Upvotes: 0