How to Generate and Read Sitemap XML File – Laravel 9 Tutorial

Laravel 9 dynamic XML sitemap tutorial. Let’s discuss how to create a dynamic sitemap.xml file in your Laravel application. We also discuss how to describe, generate, and read sitemap XML files in the Laravel application.

However, before we start breaking the ice, let me explain what the XML sitemap is and how important it is to add the sitemap xml file in the Laravel app.

SEO and Sitemaps

Generically, we all have heard about SEO, and this is not just a keyword. It decides the popularity of web applications and also decides the ranking of your site on different search engines.

Therefore, one most important tasks is to ramp up our site SEO so that it ranks better.

Many different factors amplify a site’s SEO. For instance, adding a sitemap XML file is one that we will go through and learn in this tutorial.

Why Need Sitemap Xml?

Eventually, we got to know why the XML sitemap is important. Now, let’s understand what actually sitemaps are.

A Sitemap is a file ending with a .xml extension. It is a simple file that has data about the most important website pages. Moreover, it also allows the webmaster to inform search engines what pages are available for crawling.

The sitemap file is not just limited to Laravel. Whatever technology you are using, you can use them. However, always ensure you generate and add a sitemap XML file to inform search engines.

Sitemap Archetype

Here is the logical structure of a sitemap file. We will go through a step-by-step tutorial about every property being used in the following sitemap file.

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
   <url>
      <loc>http://www.test.com/</loc>
      <lastmod>2021-03-05</lastmod>
      <changefreq>monthly</changefreq>
      <priority>0.8</priority>
   </url>
</urlset> 
  • It starts with an opening <urlset> tag relatively with ending </urlset>closing tag.
  • The xmlns property used to define the namespace prefix inside the <urlset> tag.
  • The XML contains url entry for every URL that should be added in the Sitemap.
  • The loc property is the child value of the URL that holds the web page URL.
  • The lastmod attribute is the child element of url, which reveals when was the page last modified.
  • The changefreq and priority attributes are relative child values of the URL property, these props inform search engines about the crawling priority and update frequencies.

Read & Generate Sitemap XML File in Laravel 9

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

Install Laravel Project

The command given below installs a brand new Laravel application in an amply clean manner.

composer create-project --prefer-dist laravel/laravel laravel-blog

Register Database Details

Storing and saving data in the database requires establishing a database connection. This can be done by adding the database name, username, and password in the .env configuration file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_user_name
DB_PASSWORD=database_password

If you are using MAMP local server in macOS. Make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Create Model and Migration

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

For the demonstration purpose, create a blog table with url (web page url) and description values, 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, add 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 set off, just hit the command below from your terminal and launch the new table into the database.

php artisan migrate

Add Dummy Data

Now you can add test data into your table, this will help create the URL or slug to generate an XML sitemap. However, you can skip this whole section if you have real data to make the web pages.

php artisan make:factory BlogFactory --model=Blog

This faker library provides many different methods to create test data. Nonetheless, we can take the help of the randomNumber() method to generate 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 everything is set, use the tinker commands to populate data into the database.

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

Generate and Set Up Controller

The php artisan’s command line offers an entirely clean and easy solution to generate controllers and other important files. Let’s generate a new controller with the suggested command.

php artisan make:controller SitemapXmlController

The index() function gets the blog data and immaculately insert 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');
      }
}

Register Route

Next, please move to the routes/web.php file; inside here, define the route with the get method; it helps us read the xml sitemap file on the browser.

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SitemapXmlController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/
Route::get('/sitemap.xml', [SitemapXmlController::class, 'index']);

Display Sitemap URL in Laravel

In the last section of this comprehensive guide, we will explain to you how to show sitemap XML or read sitemap XML files in the browser using the Laravel blade file. Make sure to create a new index.php file in the resources/Views/ folder.

Next, add the code given below in the resources/Views/index.blade.php file.

<?php echo '<?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>

Start Laravel Application

Lastly, we have to kill two birds with the same stone. First, start the Laravel application using the php artisan serve command. Secondly, view the sitemap XML using the below URL.

php artisan serve
http://127.0.0.1:8000/sitemap.xml
Laravel XML Sitemap

Conclusion

In this Laravel sitemap XML tutorial, we have seen an important concept that primarily belongs to SEO, and we understood how to generate a sitemap XML file in Laravel.

Not only this, we have also learned how to read the XML sitemap in a Laravel view using the traditional Laravel MVC pattern. We assume you liked this guide and will share your precious feedback with us. Have a great day!