How to Create an XML Sitemap in Laravel

Creating a simple xml sitemap in Laravel application involves generating an XML file that lists all the URLs of site to be indexed by search engines. Here’s a step-by-step guide to create a basic sitemap:

Laravel XML Sitemap

Step 1: Create a Controller for Sitemap

First, create a controller that will generate the sitemap. Run the following command in your terminal:

php artisan make:controller SitemapController

Step 2: Define the Sitemap Generation Logic

Open the newly created controller (SitemapController.php) and add the following code:

@php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
class SitemapController extends Controller
{
public function index()
{
$urls = [
url('/'),
url('/about'),
url('/contact'),
// Add more URLs as needed
];
$content = view('sitemap', compact('urls'));
return Response::make($content, 200)->header('Content-Type', 'application/xml');
}
}
@endphp

Step 3: Create the Sitemap View

Create a new view file named sitemap.blade.php in the resources/views directory with the following content:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
@foreach ($urls as $url)
<url>
<loc>{{ $url }}</loc>
</url>
@endforeach
</urlset>

Step 4: Define a Route

Next, define a route in your routes/web.php file to point to the sitemap controller:

use App\Http\Controllers\SitemapController;
Route::get('/sitemap.xml', [SitemapController::class, 'index']);

Step 5: Test the Sitemap

Now, you should be able to access your sitemap at http://yourdomain.com/sitemap.xml.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Need Help ? Call Our award-winning support team 24/7 at 01-4983900

© 2023 All right reserved to sobiztrend.com