Laravel 8 Generate and Read Sitemap XML File Tutorial

 Laravel dynamic XML sitemap Throughout this tutorial we will talk about creating a dynamic sitemap.xml file in the laravel app. More over, we also like to describe how to read the sitemap xml file in the laravel application.

But before, 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 heard about SEO, and this is not just a keyword; rather, this word decides popularity of web application. SEO decides the ranking of the site on the search engines. Therefore, our most imp task is to ramp up the site SEO so that it ranks better.

There are the multiple factors that amplify the site SEO; adding a sitemap xml file is one such factor we will learn in this tutorial.

Why Need Sitemap Xml?

Eventually we got to know why xml sitemap carries weight now, let's understand what sitemaps are? sitemap ideally is the file that end with the .xml extension; it is a simple file that contains the important website pages and allows the webmaster to inform search engines what pages are available for crawling. This sitemap file is not just limited to laravel no matter what technology you are using but make sure you must generate and add a sitemap xml file to inform search engines.

Sitemap Archetype

Here is the logical structure of sitemap file; we will explain bit by bit 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> 
Markup
  • 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 needs to be added in the Sitemap.
  • The loc property is the child value of url which 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 let search engine about the crawling priority and update frequencies.

How to Generate and Read Sitemap XML File in Laravel 8

  • 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 installs a brand new laravel application in an amply clean manner.

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

Register Database Details

Storing and saving data into the database requires establishing the database connection; it can be done by adding database name, username, and password in .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
Bash

Create 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, 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'
    ];
}
PHP

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');
    }
}
PHP

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
Bash

Add Dummy Data

Next, add the test data into the table; this will help create the url or slug for generating xml sitemap. However, you may skip this whole section if you have real data to make the web pages.

php artisan make:factory BlogFactory --model=Blog
Bash

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
        ];
    }
}
PHP

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

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

Generate and Set Up Controller

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

php artisan make:controller SitemapXmlController
Bash

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');
      }

}
PHP

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']);
PHP

Display Sitemap Url in Laravel

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

Right after that, add the given code 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>
PHP

Start Laravel Application

At last, we have to kill the two birds with the same stone; first, start the laravel app using the php artisan serve command; secondly, view the sitemap xml using the below url.

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

Laravel XML Sitemap

Post a Comment

Previous Post Next Post