Laravel 9 dynamic XML sitemap tutorial. Let’s talk about creating a dynamic sitemap.xml file in the Laravel application. Moreover, we also like to describe how to generate and read sitemap xml file 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 heard about SEO, and this is not just a keyword. This word decides the popularity of web applications. SEO decides the ranking of your site on the search engines.
Therefore, our most important task is to ramp up the site SEO so that it ranks better.
There are multiple factors that amplify the site SEO. For example, adding a sitemap xml file is one such factor we are learning in this tutorial.
Why Need Sitemap Xml?
Eventually, we got to know why xml sitemap carries weight; now, let us understand what sitemaps are?
Sitemap ideally is a file that ends with a .xml extension. It is a simple file that contains the important website pages. In addition, it allows the webmaster to inform search engines what pages are available for crawling.
The sitemap file is not just limited to Laravel. In fact, whatever technology you are using, you can use them. However, 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 step by step 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 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 Read and 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 following command 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 into the database requires establishing the database connection. This 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
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 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'
];
}
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
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
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()
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
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 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>
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
http://127.0.0.1:8000/sitemap.xml

Conclusion
In this pragmatic laravel sitemap xml tutorial, we touched on the important concept that primarily belongs to SEO, and we understood how to generate a sitemap xml file in laravel.
Not just that, we also learned how to read the xml sitemap in the laravel view using the traditional laravel MVC pattern. We assume you have liked this guide and share your precious feedback with us, have a great day.