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

Laravel 9 dynamic XML sitemap tutorial; We will talk about creating a dynamic sitemap.xml file in the laravel app throughout this guide. Furthermore, we’d like to explain how to read the sitemap xml file in the laravel application.

But, before we begin, let me explain what an XML sitemap is and why it is critical to include the sitemap xml file in the Laravel app.

SEO and Sitemaps

We’ve all heard of SEO, and it’s more than just a keyword; it determines the popularity of web applications. SEO determines your website’s ranking on search engines.

As a result, our most important task is to improve the site’s SEO so that it ranks higher.

There are numerous factors that can improve the SEO of a website; adding a sitemap xml file is one of them.

Why Need Sitemap Xml?

We eventually learned why an xml sitemap is important; now, let us define sitemaps.

A sitemap is ideally a file with an .xml extension, it is a simple file that contains the important website pages and allows the webmaster to notify search engines about which pages are available for crawling.

This sitemap file is not limited to Laravel, regardless of the technology you use, you must generate and add a sitemap xml file to inform search engines.

Sitemap Archetype

Here is the logical structure of the sitemap file, we will go over each property in detail 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 begins with an opening <urlset> tag and ends with a closing </urlset> tag.
  • The xmlns property is used within the <urlset> tag to define the namespace prefix.
  • The xml file includes a url entry for each url that needs to be added to the Sitemap.
  • The loc property is a child value of url, and it contains the web page url.
  • The lastmod attribute is a child element of url that indicates when the page was last modified.
  • The priority and changefreq attributes are relative child values of the url property, these props inform search engines about crawling priority and update frequencies.

How to Generate and Read Sitemap XML File in Laravel 9

asdasd

Laravel 9 dynamic XML sitemap tutorial; We will talk about creating a dynamic sitemap.xml file in the laravel app throughout this guide. Furthermore, we’d like to explain how to read the sitemap xml file in the laravel application.

But, before we begin, let me explain what an XML sitemap is and why it is critical to include the sitemap xml file in the Laravel app.

SEO and Sitemaps

We’ve all heard of SEO, and it’s more than just a keyword; it determines the popularity of web applications. SEO determines your website’s ranking on search engines.

As a result, our most important task is to improve the site’s SEO so that it ranks higher.

There are numerous factors that can improve the SEO of a website; adding a sitemap xml file is one of them.

Why Need Sitemap Xml?

We eventually learned why an xml sitemap is important; now, let us define sitemaps.

A sitemap is ideally a file with an .xml extension, it is a simple file that contains the important website pages and allows the webmaster to notify search engines about which pages are available for crawling.

This sitemap file is not limited to Laravel, regardless of the technology you use, you must generate and add a sitemap xml file to inform search engines.

Sitemap Archetype

Here is the logical structure of the sitemap file, we will go over each property in detail 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 begins with an opening <urlset> tag and ends with a closing </urlset> tag.
  • The xmlns property is used within the <urlset> tag to define the namespace prefix.
  • The xml file includes a url entry for each url that needs to be added to the Sitemap.
  • The loc property is a child value of url, and it contains the web page url.
  • The lastmod attribute is a child element of url that indicates when the page was last modified.
  • The priority and changefreq attributes are relative child values of the url property, these props inform search engines about crawling priority and update frequencies.

How to Generate and Read 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 following command cleanly installs a brand new Laravel application.

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

Register Database Details

Storing and saving data into the database necessitates the establishment of a database connection, which can be accomplished by including 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

Create Model and Migration

Heaven and Earth execute the given command without moving, model and migration files determine the logical structure of the table that resides in the database.

Create a blog table with url (web page url) and description values for the demo, then add the following code to 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'
    ];
}

Put the same values in the database/migration/create_blogs_table.php file as well.

<?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 that the migration is ready to go, run the following command from the terminal to insert the new table into the database.

php artisan migrate

Add Dummy Data

Next, enter the test data into the table, this will help in the creation of the url or slug for generating the xml sitemap. If you have real data to create the web pages, you can skip this section entirely.

php artisan make:factory BlogFactory --model=Blog

The faker library provides numerous methods for creating test data. However, we are using the randomNumber() method to generate the url data.

Place the following code in the 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 in place, use the tinker commands to populate the data into the database.

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

Generate and Set Up Controller

The php artisan command line provides a clean and simple way to generate controllers and other important files. Create a new controller using the suggested command.

php artisan make:controller SitemapXmlController

The index() function retrieves the blog data and inserts it flawlessly into the index view, we will later use it to read the sitemap xml file. As a result, update the file app/Http/Controllers/SitemapXmlController.php.

<?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, navigate to the routes/web.php file and define the route using the get method, this allows us to read the xml sitemap file in 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

The final section of this comprehensive guide will explain how to use the laravel blade file to display or read a sitemap xml file in the browser. Make a new index.php file in the resources/Views/ directory.

After that, paste the following code into 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

Finally, we must kill two birds with one stone: first, start the laravel app with the php artisan serve command, and then view the sitemap xml with the url below.

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

Conclusion

In this practical laravel sitemap xml tutorial, we covered an important concept related to SEO and learned how to create a sitemap xml file in laravel.

Not only that, but we also learned how to read an xml sitemap in a Laravel view using the traditional MVC pattern. We hope you enjoyed this guide and will share your valuable feedback with us, have a wonderful day.

2 Comments

Leave a Reply