orderBy('updated_at', 'desc')->chunk(500, function ($books) use (&$urls) { foreach ($books as $book) { $urls[] = [URL::to('/books/' . $book->slug), optional($book->updated_at)]; } }); $xml = $this->buildXml($urls); return response($xml, 200)->header('Content-Type', 'application/xml'); } /** * Build a basic XML sitemap string. * * @param array $urls */ protected function buildXml(array $urls): string { $xmlHeader = ''; $urlsetOpen = ''; $urlsetClose = ''; $body = ''; foreach ($urls as [$loc, $lastmod]) { $body .= "\n \n"; $body .= ' ' . e($loc) . "\n"; if ($lastmod) { $body .= ' ' . $lastmod->format('c') . "\n"; } $body .= " "; } return $xmlHeader . "\n" . $urlsetOpen . $body . "\n" . $urlsetClose . "\n"; } }