xxxxxxxxxx
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;
}
}
1. Install the Laravel Sitemap Package: First, you need to install a package that helps in generating sitemaps. A popular choice is the spatie/laravel-sitemap package. You can install it using Composer:
xxxxxxxxxx
composer require spatie/laravel-sitemap
2. Create Sitemap Route: Create a route in your web.php file that will handle the sitemap generation:
xxxxxxxxxx
Route::get('sitemap.xml', 'SitemapController@index');
3. Create a Sitemap Controller: Create a new controller called SitemapController using Artisan:
xxxxxxxxxx
php artisan make:controller SitemapController
4. In your SitemapController, you'll need a method to generate the sitemap. Here's an example:
xxxxxxxxxx
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;
use App\Models\Post;
class SitemapController extends Controller
{
public function index()
{
$sitemap = Sitemap::create();
// Add static URLs
$sitemap->add('/');
// Add dynamic URLs from your database or other sources
$posts = Post::all();
foreach ($posts as $post) {
$sitemap->add(Url::create('/post/' . $post->id)->setLastModificationDate($post->updated_at));
}
// Return the sitemap as a response
return $sitemap->render();
}
}
5. Testing: You can test your sitemap by visiting the /sitemap.xml route in your browser. You should see the generated sitemap XML.
6. If you want to save the sitemap to a file.
xxxxxxxxxx
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;
use App\Models\Post;
class SitemapController extends Controller
{
public function index()
{
$sitemap = Sitemap::create();
// Add static URLs
$sitemap->add('/');
// Add dynamic URLs from your database or other sources
$posts = Post::all();
foreach ($posts as $post) {
$sitemap->add(Url::create('/post/' . $post->id)->setLastModificationDate($post->updated_at));
}
// Store the sitemap to a file
$sitemap->writeToFile(public_path('sitemap.xml'));
return 'Sitemap generated and saved to sitemap.xml';
}
}