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

Sitemap Laravel Package

laravelium/sitemap

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require laravelium/sitemap
    

    For Laravel, publish the config (optional):

    php artisan vendor:publish --provider="Laravelium\Sitemap\SitemapServiceProvider"
    
  2. Basic Usage: Define a route to generate the sitemap:

    use Laravelium\Sitemap\Facades\Sitemap;
    
    Route::get('/sitemap.xml', function () {
        return Sitemap::create()
            ->add(url('/'), 1.0, 'daily')
            ->add(url('/about'), 0.8, 'weekly')
            ->render('xml');
    });
    
  3. First Use Case: Generate a simple XML sitemap for core routes. Test locally by visiting /sitemap.xml.


Implementation Patterns

Core Workflows

  1. Dynamic Sitemap Generation: Use closures to fetch dynamic URLs (e.g., blog posts):

    Sitemap::create()
        ->add(url('/posts'), 0.7, 'monthly')
        ->add(url('/posts/{id}'), 0.9, 'weekly', function ($sitemap) {
            return Post::all()->map(fn ($post) => $post->slug);
        });
    
  2. Multi-Language Support: Add hreflang tags for translated content:

    $sitemap->add(url('/post'), 1.0, 'daily')
        ->setLanguage('en')
        ->addAlternate(url('/post-es'), 'es');
    
  3. Image/Video Sitemaps: Extend the base class for rich media:

    use Laravelium\Sitemap\SitemapGenerator;
    use Laravelium\Sitemap\Items\Image;
    
    class VideoSitemap extends SitemapGenerator {
        public function addVideo($url, $title, $description) {
            return $this->add($url, 1.0, 'daily')
                ->addVideo($title, $description, url('/video-thumbnail.jpg'));
        }
    }
    
  4. Caching: Cache generated sitemaps for performance:

    Route::get('/sitemap.xml', function () {
        return Cache::remember('sitemap-xml', now()->addHours(6), function () {
            return Sitemap::create()->add(...)->render('xml');
        });
    });
    

Integration Tips

  • Laravel Routes: Use Route::get() for public sitemaps or Route::middleware(['auth']) for private ones.
  • Queue Jobs: Offload sitemap generation to a queue for large sites:
    dispatch(new GenerateSitemapJob());
    
  • Testing: Mock the Sitemap facade in unit tests:
    $sitemap = Mockery::mock(Laravelium\Sitemap\Facades\Sitemap::class);
    $sitemap->shouldReceive('render')->andReturn('<xml>...</xml>');
    

Gotchas and Tips

Common Pitfalls

  1. URL Validation:

    • Ensure URLs are absolute (e.g., url('/path') instead of /path). Relative URLs may break validation.
    • Use str()->startsWith('http') to validate URLs before adding them.
  2. Change Frequency:

    • Avoid always for large collections (e.g., product pages). Use weekly or monthly instead.
    • Google ignores changefreq if lastmod is missing.
  3. Memory Limits:

    • Large sitemaps (>50MB) may hit PHP’s memory limit. Split into multiple files:
      Sitemap::create()->setLimit(3000)->render('xml'); // Max 3000 URLs per file
      
  4. Caching Headers:

    • Set Cache-Control headers to prevent proxy caching issues:
      return response(Sitemap::render('xml'))
          ->header('Cache-Control', 'public, max-age=86400');
      

Debugging Tips

  • Validate XML: Use an online validator (e.g., XML Validation) to catch malformed output.
  • Log Errors: Wrap sitemap generation in a try-catch to log issues:
    try {
        return Sitemap::create()->add(...)->render('xml');
    } catch (\Exception $e) {
        Log::error('Sitemap generation failed: ' . $e->getMessage());
        return response('Error generating sitemap.', 500);
    }
    

Extension Points

  1. Custom Items: Extend Laravelium\Sitemap\Items\Url for custom metadata:

    class CustomUrl extends Url {
        public function setCustomTag($name, $value) {
            $this->customTags[$name] = $value;
        }
    }
    
  2. Adapters: Override the default XmlWriter adapter for custom formats:

    use Laravelium\Sitemap\Adapters\AdapterInterface;
    
    class JsonAdapter implements AdapterInterface {
        public function render(array $items) {
            return json_encode($items);
        }
    }
    
  3. Service Provider: Bind custom sitemap classes in the service provider:

    $this->app->bind('custom.sitemap', function () {
        return new CustomSitemap();
    });
    

Config Quirks

  • Default Priority: The package defaults to 0.5 if not specified. Explicitly set priorities for critical pages (e.g., 1.0 for homepages).
  • Timezones: Ensure lastmod timestamps use UTC to avoid timezone-related issues:
    $sitemap->add(url('/post'), 1.0, 'daily', now()->tz('UTC'));
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle