Install Dependencies
Install the dependencies using composer. By default, it will install the latest version of the package, but if you are using an old version of Laravel, do specify the suitable version for your project.
composer require laravelium/sitemap
php artisan vendor:publish --provider="Laravelium\Sitemap\SitemapServiceProvider"
Implementation
To generate the sitemap define a new route and call it "sitemap" so the URL that's publicly accessible is "yourapp.test/sitemap". Inside the body of this route, retrieve the sitemap instance and this instance has several methods such as add, render and store.
$sitemap = app('sitemap');
/** add item to the sitemap (url, date, priority, freq) */ $sitemap->add(url('/'), now(), '1.0', 'weekly'); $sitemap->add(url('posts'), now(), '0.8', 'monthly');
Post::query() ->get() ->each(fn($post) => $sitemap->add( route('posts.show', ['slug' => $post->slug]), $post->updated_at, '0.7', 'monthly', [ /* If your post has image (e.g. cover) that you want to be indexed */ [ 'url' => $post->cover_url, 'title' => $post->title, 'caption' => $post->caption, ] ] ));
return $sitemap->render('xml');
Final Code
By now your code will look like this and do visit "/sitemap" path in your application to view the rendered sitemap.
Route::get('sitemap', function () { $sitemap = app('sitemap'); /** add item to the sitemap (url, date, priority, freq) */ $sitemap->add(url('/'), now(), '1.0', 'weekly'); $sitemap->add(url('posts'), now(), '0.8', 'monthly'); Post::query() ->get() ->each(fn($post) => $sitemap->add( route('posts.show', ['slug' => $post->slug]), $post->updated_at, '0.7', 'monthly', [ /* If your post has image (e.g. cover) that you want to be indexed */ [ 'url' => $post->cover_url, 'title' => $post->title, 'caption' => $post->caption, ] ] )); return $sitemap->render('xml'); });
$sitemap->store('xml');