𝗛𝗼𝘄 𝘁𝗼 𝗚𝗲𝗻𝗲𝗿𝗮𝘁𝗲 𝗮 𝗦𝗶𝘁𝗲𝗺𝗮𝗽 𝗶𝗻 𝗟𝗮𝗿𝗮𝘃𝗲𝗹

Search engines use sitemaps to find and index your pages. A sitemap is an XML file. It tells Google and Bing which URLs exist on your site.

You can build a sitemap in Laravel using the Spatie Sitemap package.

Follow these steps to set it up.

  1. Install the package Run this command in your terminal: composer require spatie/laravel-sitemap

  2. Create a controller Generate a new controller to handle the logic: php artisan make:controller GenerateSitemap

  3. Write the logic Open your new controller and add this code:

namespace App\Http\Controllers;

use Spatie\Sitemap\Sitemap; use Spatie\Sitemap\Tags\Url; use App\Models\Post;

class GenerateSitemap extends Controller { public function index() { $sitemap = Sitemap::create();

$sitemap->add( Url::create('/') ->setPriority(1.0) ->setChangeFrequency(Url::CHANGE_FREQUENCY_DAILY) );

Post::with('category') ->where('status', 1) ->latest() ->get() ->each(function ($post) use ($sitemap) { $sitemap->add( Url::create($post->category->slug . '/' . $post->slug) ->setLastModificationDate($post->updated_at) ->setPriority(0.9) ->setChangeFrequency(Url::CHANGE_FREQUENCY_WEEKLY) ); });

$sitemap->writeToFile(public_path('sitemap.xml'));

return back()->with('success', 'Sitemap Generated!'); } }

What this code does:

  • It creates a new sitemap object.
  • It adds your homepage with high priority.
  • It loops through your database posts.
  • It adds every post URL to the file.
  • It saves the file to your public folder as sitemap.xml.

Your sitemap will live at yourdomain.com/sitemap.xml.

This helps search engines find your new content quickly.

Source: https://dev.to/mindwarezone/how-to-generate-a-sitemap-in-laravel-a-complete-guide-4go6