Laravel 10 Generate and Read Sitemap XML File Tutorial - TechvBlogs

Laravel 10 Generate and Read Sitemap XML File Tutorial

Discover how to create and use XML sitemaps in Laravel 10 for better SEO results. Learn the basics of generating and reading sitemap files with ease.


Suresh Ramani - Author - TechvBlogs
Suresh Ramani
 

2 months ago

In this article, we'll walk you through the process of making a dynamic sitemap.xml file for your Laravel application and show you how Laravel uses it. But first, let's break down what an XML sitemap is and why it's essential for your Laravel website.

What is an XML Sitemap?

An XML sitemap is like a map for your website that search engines, like Google, use to navigate and understand your site better. Imagine it as a table of contents for your website that helps search engines find and index all your web pages. This makes it easier for people to discover your site when they search online.

Why Need Sitemap XML?

Having an XML sitemap for your Laravel website is crucial for a few reasons:

  1. Improved Visibility: Search engines can find and rank your pages more effectively when you have a sitemap. This means more people can discover your site.

  2. Better SEO: It helps improve your site's search engine optimization (SEO) by ensuring all your important pages are indexed.

  3. Faster Updates: When you add new content or make changes, a sitemap helps search engines quickly recognize these updates.

Sitemap Archetype

A sitemap archetype typically refers to a standard or common structure or format used for creating XML sitemaps. An XML sitemap is a file that provides information to search engines about the pages on your website, helping them index and understand your site's content. While there isn't a single "archetype" for sitemaps, there are widely accepted guidelines and elements that sitemaps typically contain:

  1. URLs: Each URL of your website that you want to be indexed should be listed in the sitemap.

  2. Last Modification Date: You can include the date when each page was last modified. This helps search engines understand when your content was updated.

  3. Change Frequency: You can indicate how often a page is likely to change (e.g., daily, weekly, monthly).

  4. Priority: You can assign a priority value to each URL to indicate its relative importance on your site.

Here's a basic example of what an XML sitemap might look like:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
   <url>
      <loc>https://www.example.com/page1</loc>
      <lastmod>2023-09-01</lastmod>
      <changefreq>weekly</changefreq>
      <priority>0.8</priority>
   </url>
   <url>
      <loc>https://www.example.com/page2</loc>
      <lastmod>2023-08-15</lastmod>
      <changefreq>monthly</changefreq>
      <priority>0.7</priority>
   </url>
   <!-- More URLs go here -->
</urlset>

This XML file follows the sitemap protocol guidelines and contains URLs, their last modification dates, change frequencies, and priorities. Search engines use this information to efficiently crawl and index the pages on your website.

Remember that the specific content and structure of your sitemap can vary depending on the complexity and requirements of your website. The example above is a simplified version, and real-world sitemaps can be more extensive.

How to Generate and Read Sitemap XML File in Laravel 10

  • Step 1: Install Laravel Project
  • Step 2: Configure Database Details
  • Step 3: Create a Model and Migration
  • Step 4: Add Dummy Data
  • Step 5: Generate and Set Up the Controller
  • Step 6: Register Route
  • Step 7: Display Sitemap in Laravel
  • Step 8: Start the Laravel Application

Step 1: Install Laravel Project

First, open Terminal and run the following command to create a fresh Laravel project:

composer create-project --prefer-dist laravel/laravel laravel10-sitemap-xml

or, if you have installed the Laravel Installer as a global composer dependency:

laravel new laravel10-sitemap-xml

Step 2: Configure Database Detail

open .env and update database detail

DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=<DATABASE NAME>
DB_USERNAME=<DATABASE USERNAME>
DB_PASSWORD=<DATABASE PASSWORD>

Step 3: Create a Model and Migration

Model and migration files decide the logical structure of the table that resides in the database; without moving, heaven and earth execute the given command.

For the demo purpose, create a blog table with URL (web page URL) and description values, and place the following code in the app/Models/Blog.php file.

<?php

namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Blog extends Model
{
    use HasFactory;
    
    protected $fillable = [
        'url', 
        'description'
    ];
}

Similarly, put the same values into the database/migration/create_blogs_table.php file.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateBlogsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('blogs', function (Blueprint $table) {
            $table->id();
            $table->string('url');
            $table->text('description');            
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('blogs');
    }
}

Now, the migration is ready to blast off, just hit the following command from the terminal and propel the new table into the database.

php artisan migrate

Step 4: Add Dummy Data

The test data should then be added to the table, which will aid in creating the URL or slug needed to generate an XML sitemap. If, however, you are using real data to create the web pages, you can skip the entire section.

php artisan make:factory BlogFactory --model=Blog

The faker library offers tons of methods for creating test data; nonetheless, we are taking the help of the randomNumber() method to generate the url data.

Go ahead and place the below code in database\factories\BlogFactory.php file:

<?php

namespace Database\Factories;
use App\Models\Blog;
use Illuminate\Database\Eloquent\Factories\Factory;

class BlogFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Blog::class;
    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'url' => $this->faker->randomNumber($nbDigits = NULL, $strict = false),
            'description' => $this->faker->text
        ];
    }
}

When all set, then use the tinker commands to populate the data into the database.

php artisan tinker
Blog::factory()->count(30)->create()

Step 5: Generate and Set Up the Controller

A very clear and simple way to create controllers and other crucial files is through the php artisan command line. Let's create a brand-new controller using the advised command.

php artisan make:controller SitemapXmlController

The index() function gets the blog data and immaculately inserts it into the index view; we will later access it to read the sitemap XML file. Hence, update the app/Http/Controllers/SitemapXmlController.php file.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Blog;

class SitemapXmlController extends Controller
{
    public function index() {
        $posts = Blog::all();

        return response()->view('index', [
            'posts' => $posts
        ])->header('Content-Type', 'text/xml');
      }
}

Step 6: Register Route

Please proceed to the routes/web.php file after that. Define the route using the get function inside of this file to help the browser read the xml sitemap.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SitemapXmlController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/

Route::get('/sitemap.xml', [SitemapXmlController::class, 'index']);

Step 7: Display Sitemap Url in Laravel

This detailed article will conclude with instructions on how to display or read a sitemap XML file in a browser using a Laravel Blade file. Ensure that the resources/views/ subdirectory contains a fresh index.php file.

Right after that, add the given code to the resources/views/index.blade.php file.

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    @foreach ($posts as $post)
        <url>
            <loc>{{ url('/') }}/page/{{ $post->url }}</loc>
            <lastmod>{{ $post->created_at->tz('UTC')->toAtomString() }}</lastmod>
            <changefreq>weekly</changefreq>
            <priority>0.8</priority>
        </url>
    @endforeach
</urlset>

Step 8: Start Laravel Application

Finally, we need to use the php artisan serve command to launch the Laravel app and the following URL to examine the sitemap XML.

php artisan serve
http://127.0.0.1:8000/sitemap.xml

Conclusion

We touched on an important idea that mostly pertains to SEO in this practical Laravel sitemap XML tutorial, and we learned how to create a sitemap XML file in Laravel.

Not only that, but we also learned how to use the conventional Laravel MVC pattern to read the XML sitemap in the Laravel view. We sincerely hope you enjoyed this guide and will give us your thoughtful opinion. Enjoy the rest of your day.

Comments (0)

Comment


Note: All Input Fields are required.