We will discuss generating a dynamic sitemap.xml file in the laravel app throughout this article on establishing a dynamic XML sitemap for Laravel 9. In addition, we'd like to explain how the Laravel application reads the sitemap xml file.
But before we get started, let me describe what an XML sitemap is and why it's crucial to have one in a Laravel application.
Sitemaps and SEO
We've all heard of SEO, however this term determines the popularity of online applications rather than just being a simple keyword. Your website's position in the search engine results depends on SEO.
Therefore, improving the SEO of the site in order to improve rankings is our top priority.
A sitemap xml file is one of the many variables that boost a website's SEO, and we will learn about it in this lesson.
Why Is a Sitemap XML Needed?
Finally, we learned why an xml sitemap is important; now, can you explain what a sitemap is?
A sitemap is a straightforward file with an extension of.xml that comprises the key web pages of a website and enables the webmaster to tell search engines which pages are accessible for crawling.
No matter what technology you are using, you must create and add a sitemap xml file to inform search engines. This sitemap file is not simply limited to Laravel.
Website Map Type
Here is the sitemap file's logical structure; we will go over each property utilized in the following sitemap file bit by bit.
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.codesolutionstuff.com/</loc>
<lastmod>2022-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 namespace prefix inside the urlset> tag is defined by the xmlns property.
- Every url that has to be included to the Sitemap is listed in the xml.
- The web page url is stored in the loc property, which is a child value of url.
- The child element of url has a lastmod attribute that indicates when the page was latest changed.
- The relative child values of the url property are the changefreq and priority attributes. These props inform search engines about the crawling priorities and update frequencies.
Table of Contents
- Install Laravel Project
- Register Database Details
- Create Model and Migration
- Add Dummy Data
- Generate and Set Up Controller
- Register Route
- Display Sitemap in Laravel
- Start Laravel Application
Install Laravel Project
composer create-project --prefer-dist laravel/laravel laravel-blog
Register Database Details
Establishing the database connection is necessary for storing and saving data into the database; you can accomplish this 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
The logical structure of the table that is stored in the database is determined by model and migration files; without moving, heaven and earth carry out the provided order.
The following code should be added to the app/Models/Blog.php file to establish a blog table for the demo that has values for the url (web page url) and description.
<?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'
];
}
The database/migration/create blogs table.php file should also include the same settings.
<?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 complete, you may launch it into space by typing the following command into your terminal. This will insert the new table into the database.
php artisan migrate
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
Although the faker package has a tonne of options for producing test data, we are using the randomNumber() function to produce the url data.
Put the following code in the file database\factories\BlogFactory.php:
<?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
];
}
}
Once everything is ready, use the Tinker instructions to add the data to the database.
php artisan tinker
Blog::factory()->count(30)->create()
Generate and Set Up 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 sitemap xml file will eventually be accessed in order to read the blog data that the index() function meticulously inserts into the index view. Therefore, change the sitemapXmlController.php file located under app/Http/Controllers.
<?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
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']);
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.
Add the following code to the resources/Views/index.blade.php file after that.
<?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 need to use the php artisan serve command to launch the laravel app and the following url to examine the sitemap xml, which will allow us to kill two birds with one stone.
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 learnt 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.