file($path, [ 'Content-Type' => 'application/xml', ]); } public function generate(Request $request) { $path = public_path('sitemap.xml'); $sitemapConfig = SitemapConfig::active()->latest()->first(); $sitemapExcludes = $sitemapConfig->sitemap_excludes; $ignoreRobots = $sitemapConfig->ignore_robot; if (is_string($sitemapExcludes)) { $sitemapExcludes = array_map('trim', explode(',', $sitemapExcludes)); } $generator = SitemapGenerator::create(config('app.url')) ->configureCrawler(function (Crawler $crawler) use ($ignoreRobots, $sitemapConfig) { if ($ignoreRobots) { $crawler->ignoreRobots(); } if ($sitemapConfig->max_depth) { $crawler->setMaximumDepth($sitemapConfig->max_depth); } }) ->shouldCrawl(function (UriInterface $url) use ($sitemapExcludes) { $path = $url->getPath(); foreach ($sitemapExcludes as $exclude) { if (str_starts_with($path, $exclude)) { return false; } } return true; }); if ($sitemapConfig->max_crawl_count) { $generator->setMaximumCrawlCount($sitemapConfig->max_crawl_count); } $generator->writeToFile($path); if (!file_exists($path)) { return response('Failed to generate sitemap.', 404); } return response()->file($path, [ 'Content-Type' => 'application/xml', ]); } }