Good content takes time and effort to come up with.

Please consider supporting us by just disabling your AD BLOCKER and reloading this page again.







Generate Sitemap in PHP Laravel


Share On     Share On WhatsApp     Share On LinkedIn


In the current trend most of the developers or bloggers are fascinated towards using CMS whether it might be Wordpress, October CMS, Drupal, Joomla etc... for writing their blog or publish articles. SEO is key to reaching to as many as possible. One of the main important point to keep in mind when doing SEO is SITEMAP generation.


Major CMS's have this feature built and can be automatically generate or can be generated with few clicks. But today I will be showing you how to create a sitemap with PHP Laravel.


Prerequisites


I hope you might have built blog , website or documentation site with LARAVEL. If you want to just setup up server and play around then go ahead and do in Digital Ocean, Linode or any other cloud platform.


Step 1 - Install laravel-sitemap Package


More details on the package you can find in this GitHub repository link Laravel Sitemap but as of now you can follow along with me.


Installation


Be sure your in root folder of your LARVEL project and run the following composer command


composer require spatie/laravel-sitemap


The above command basically creates composer.json file if not exists, if exists then it writes in require key of composer.json as follows


"require": {
    "spatie/laravel-sitemap": "^5.7"
}


Even this record will be written in composer.lock so keep in mind that if your developing in your personal computer to push it to production server.


Step 2 - Lets Run It


Now our package is installed. Just to make sure that it will work fine as expected. You can test in web.php


use Spatie\Sitemap\SitemapGenerator;

Route::get('/sitemap', function(){
  /** The following line creates sitemap.xml in public folder based on your website_url  */
  SitemapGenerator::create('http://website_url')->writeToFile('sitemap.xml');
);
  


Once you go to browser and run http://website_url/sitemap this will create sitemap.xml in public folder of Laravel.


The above code automatically scans the website_url and check for all the links to add to sitemap.xml but if you want to add specific URL's or dynamically add url based on some condition then do the following


use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;

$sitemap = Sitemap::create()
    ->add(Url::create('/newsletter'))
    ->add(Url::create('/contact_us'))
    ->add(Url::create('/posts'));
/** Now you haved added custom URL's, now add dynamic URL's for SEO */
$posts = Posts::published()->get();
foreach ($posts as $post) {
    $sitemap->add(Url::create("/post/{$post->slug}"));
}
$sitemap->writeToFile(public_path('sitemap.xml'));


The above codes custom sitemap.xml based on you needs. You can add multiple other stuff to make it more dynamic and customised as per your needs.


Step 3 - Automate Sitemap Generation


If your writing blogs daily then generating the sitemap daily will be a big task for you so you can automate it with the Laravel very easily with artisan command


php artisan make:command GenerateSitemap 


This creates a GenerateSitemap in App\Console\Commands folder with name GenerateSitemap. Now open this file and add the following code


use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;

protected $signature = 'sitemap:generate';

protected $description = 'Generate the sitemap';

public function handle()
    {
        $sitemap = Sitemap::create()
            ->add(Url::create('/newsletter'))
            ->add(Url::create('/contact_us'))
            ->add(Url::create('/posts'));
        $posts = Post::published()->get();
        foreach ($posts as $post) {
            $sitemap->add(Url::create("/posts/{$post->slug}"));
        }
        $sitemap->writeToFile(public_path('sitemap.xml'));
    }


Overall you GenerateSitemap class will look like the following


use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;

class GenerateSitemap extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sitemap:generate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate the sitemap';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $sitemap = Sitemap::create()
            ->add(Url::create('/newsletter'))
            ->add(Url::create('/contact_us'))
            ->add(Url::create('/posts'));
        $posts = Post::published()->get();
        foreach ($posts as $post) {
            $sitemap->add(Url::create("/posts/{$post->slug}"));
        }
        $sitemap->writeToFile(public_path('sitemap.xml'));
    }
}



Step 4 - Add To Laravel Task Scheduling (Cronjob)


Go to App\Console\Kernel.php file and add the following code for automating your Laravel jobs


protected function schedule(Schedule $schedule)
{
    $schedule->command('sitemap:generate')->daily();
}


The above code runs the sitemap generating code daily midnight. You can set the cronjob as per your convince time. For more details on cronjob refer this Larvel Documentation


Step 5 - Get It Working In Your Cloud Server


This is the final step you need to setup in your server cronjob scheduler


sudo crontab -e


If your editing this file for the first time then it may ask you to choose the editor. Go ahead and select your favourite one.


Now to make sure to add the following in the opened file. Please change path-to-your-project with respect to your project location. Most of the times your project will be setup in /var/www/html or /var/www/html/project_name from where you will run all your artisan commands


* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1


This Laravel task scheduler which resides in path-to-your-project and generates sitemap.xml daily and you can sit back, relax and think on your other articles.


Conclusion


Now you got to know how to generate sitemap.







Author Image
AUTHOR

Channaveer Hakari

I am a full-stack developer working at WifiDabba India Pvt Ltd. I started this blog so that I can share my knowledge and enhance my skills with constant learning.

Never stop learning. If you stop learning, you stop growing