Make Sitemap Using Laravel
A website sitemap is a file that lists all the pages of your website, providing information about their structure and content. There are two main types:
XML Sitemap: For search engines to help them crawl and index your site better.
HTML Sitemap: For users to help them navigate your site easily.
Step 1: Define a Route
Route::get('sitemap.xml', 'SitemapController@index');
Step 2: Make a Controller
Make a controller SitemapController.php
namespace App\Http\Controllers; use App\Service\Front\SitemapService; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Response; class SitemapController extends Controller { public function index() { $urls = Cache::remember(currentTheme() . 'site_map_cache', now()->addDays(7), static function () { return (new SitemapService())->generateSiteMapTemp(); }); $content = view(currentTheme() . 'sitemap', compact('urls'))->render(); return Response::make($content, 200)->header('Content-Type', 'application/xml'); } }
Step 3:Â Define a Service
This service will be called from controller along with cache feature. We have initially setup cache for 7 days
namespace App\Service\Front; use App\Helper\Status; use App\Models\Post\Post; class SitemapService { public function generateSiteMapTemp(): array { $siteMapUrls = [ ['url' => route('home'), 'changefreq' => 'daily'], ['url' => url('/category'), 'changefreq' => 'daily'], ['url' => route('page', 'privacy-policy'), 'changefreq' => 'monthly'], ['url' => route('page', 'terms-and-conditions'), 'changefreq' => 'monthly'], ]; //post url $posts = Post::select('slug')->where('status', Status::STATUS_PUBLISHED)->get(); foreach ($posts as $post) { $siteMapUrls[] = [ 'url' => route('view-post', ['slug' => $post->slug]), 'changefreq' => 'daily' ]; } return $siteMapUrls; } }
Step 4:Â Making Blade File for sitemap.xmlÂ
//sitemap.blade.php
Add below content in your sitemap.blade.php file
@foreach ($urls as $url) @endforeach {{ $url['url'] }} {{ \Carbon\Carbon::now()->toAtomString() }} {{ $url['changefreq'] }}
Step 5:Â Access sitemap.xml in Browser
http://127.0.0.1:8000/sitemap.xml