---
description: >-
  https://onlinewebtutorblog.com/laravel-9-how-to-generate-dynamic-sitemap-tutorial/
---

# Laravel 9 How To Generate Dynamic Sitemap Tutorial

## Laravel 9 How To Generate Dynamic Sitemap Tutorial

June 5, 2022 by [Sanjay Kumar](https://onlinewebtutorblog.com/author/admin/)

Table of Contents

* [Laravel Installation](https://onlinewebtutorblog.com/laravel-9-how-to-generate-dynamic-sitemap-tutorial/#Laravel_Installation)
* [Create Database & Connect](https://onlinewebtutorblog.com/laravel-9-how-to-generate-dynamic-sitemap-tutorial/#Create_Database_Connect)
* [Create Model & Migration](https://onlinewebtutorblog.com/laravel-9-how-to-generate-dynamic-sitemap-tutorial/#Create_Model_Migration)
* [Create Post Factory (Test Data)](https://onlinewebtutorblog.com/laravel-9-how-to-generate-dynamic-sitemap-tutorial/#Create_Post_Factory_Test_Data)
* [Create Controller](https://onlinewebtutorblog.com/laravel-9-how-to-generate-dynamic-sitemap-tutorial/#Create_Controller)
* [Create Template File](https://onlinewebtutorblog.com/laravel-9-how-to-generate-dynamic-sitemap-tutorial/#Create_Template_File)
* [Add Route](https://onlinewebtutorblog.com/laravel-9-how-to-generate-dynamic-sitemap-tutorial/#Add_Route)
* [Application Testing](https://onlinewebtutorblog.com/laravel-9-how-to-generate-dynamic-sitemap-tutorial/#Application_Testing)

Share this Article

*
*
*
*
*

Reading Time: 6 minutes 50 Views

Inside this article we will see the concept i.e Laravel 9 How to generate dynamic sitemap tutorial. This article contains classified information about generating a **sitemap.xml** for a laravel application.

**A sitemap lists a website’s most important pages, thus, making sure search engines can find and crawl them**. Sitemaps also help in understanding your website structure, making it easier to navigate your website.

If you are wondering to find a solution to generate dynamic sitemap for laravel 9 application.

Learn More –

* [Laravel 9 View Logs Using LogViewer Package Tutorial](https://onlinewebtutorblog.com/laravel-9-view-logs-using-logviewer-package-tutorial/)
* [Laravel 9 How To Work with Ajax Post Request](https://onlinewebtutorblog.com/laravel-9-how-to-work-with-ajax-post-request/)
* [Laravel 9 How to Work with Telescope Tutorial](https://onlinewebtutorblog.com/laravel-9-how-to-work-with-telescope-tutorial/)
* [Laravel 9 HTTP cURL DELETE Request Tutorial](https://onlinewebtutorblog.com/laravel-9-http-curl-delete-request-tutorial/)

Let’s get started.

### Laravel Installation

Open terminal and run this command to create a laravel project.

```
$ composer create-project laravel/laravel myblog
```

It will create a project folder with name **myblog** inside your local system.

To start the development server of laravel –

```
$ php artisan serve
```

URL: http://127.0.0.1:8000

**Assuming laravel already installed inside your system.**

### Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

```
CREATE DATABASE laravel_app;
```

To connect database with application, Open **.env file** from application root. Search for **DB\_** and update your details.

```
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=root
```

### Create Model & Migration

Open project into terminal and run this command.

```
$ php artisan make:model Post -m
```

This command will create two files.

![](https://assets.vlitag.com/widget/2019/11/05/1572962830.jpg)00:00/03:27

* A model file **Post.php** inside /app/Models folder.
* A migration file 2022\_04\_26\_013730\_**create\_posts\_table.php** inside /database/migrations folder.

Open xxx\_create\_posts\_table.php migration file and write this code into it. This will create **posts** table into database.

xxx\_create\_posts\_table.php

```
<?php
```

```
​
```

```
use Illuminate\Database\Migrations\Migration;
```

```
use Illuminate\Database\Schema\Blueprint;
```

```
use Illuminate\Support\Facades\Schema;
```

```
​
```

```
return new class extends Migration
```

```
{
```

```
    /**
```

```
     * Run the migrations.
```

```
     *
```

```
     * @return void
```

```
     */
```

```
    public function up()
```

```
    {
```

```
        Schema::create('posts', function (Blueprint $table) {
```

```
            $table->id();
```

```
            $table->string('title');
```

```
            $table->string('slug');
```

```
            $table->text('body');
```

```
            $table->timestamps();
```

```
        });
```

```
    }
```

```
​
```

```
    /**
```

```
     * Reverse the migrations.
```

```
     *
```

```
     * @return void
```

```
     */
```

```
    public function down()
```

```
    {
```

```
        Schema::dropIfExists('posts');
```

```
    }
```

```
};
```

```
​
```

#### Run Migration

Back to project terminal and run this command to migrate migrations.

```
$ php artisan migrate
```

It will run all migrations and create their respective tables.

Table: **posts**

![](https://onlinewebtutorblog.com/wp-content/uploads/2022/06/how-to-create-dynamic-sitemap-in-laravel-9-tutorial.png?ezimgfmt=rs:411x303/rscb5/ng:webp/ngcb5)

Open **Post.php** model file from /app/Models folder. Write this code into it.

Posts.php

```
<?php
```

```
​
```

```
namespace App\Models;
```

```
​
```

```
use Illuminate\Database\Eloquent\Factories\HasFactory;
```

```
use Illuminate\Database\Eloquent\Model;
```

```
​
```

```
class Post extends Model
```

```
{
```

```
    use HasFactory;
```

```
​
```

```
    protected $fillable = [
```

```
        'title', 'slug', 'body'
```

```
    ];
```

```
}
```

```
​
```

### Create Post Factory (Test Data)

Next,

We will create a factory file by the help of which we can create test data for this laravel application.

```
$ php artisan make:factory PostFactory
```

It will create a file **PostFactory.php** file inside **/database/factories** folder.

Open file and write this complete code into it.

PostFactory.php

```
<?php
```

```
​
```

```
namespace Database\Factories;
```

```
​
```

```
use Illuminate\Database\Eloquent\Factories\Factory;
```

```
use Illuminate\Support\Str;
```

```
​
```

```
/**
```

```
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Post>
```

```
 */
```

```
class PostFactory extends Factory
```

```
{
```

```
    /**
```

```
     * Define the model's default state.
```

```
     *
```

```
     * @return array<string, mixed>
```

```
     */
```

```
    public function definition()
```

```
    {
```

```
        return [
```

```
            'title' => $this->faker->text(),
```

```
            'slug' => Str::slug($this->faker->text()),
```

```
            'body' => $this->faker->paragraph()
```

```
        ];
```

```
    }
```

```
}
```

```
​
```

#### Run Factory File – Seed Data

We will use **tinker shell** to run factory and generate application’s fake data.

Back to project terminal and execute these commands –

```
$ php artisan tinker
```

It will open tinker shell. Next, run this command to create 50 fake rows for **posts** table.

```
>>> App\Models\Post::factory()->count(50)->create();
```

Above command will insert 50 fake rows.

![](https://onlinewebtutorblog.com/wp-content/uploads/2022/06/generate-dynamic-sitemap-from-laravel-9-database-1024x383.png?ezimgfmt=rs:725x271/rscb5/ng:webp/ngcb5)

### Create Controller

Next,

Back to terminal and run this artisan command for controller file.

```
$ php artisan make:controller SitemapController
```

It will create **SitemapController.php** file inside /app/Http/Controllers folder.

Open file and write this complete code into it.

SitemapController.php

```
<?php
```

```
​
```

```
namespace App\Http\Controllers;
```

```
​
```

```
use Illuminate\Http\Request;
```

```
use App\Models\Post;
```

```
​
```

```
class SitemapController extends Controller
```

```
{
```

```
    public function index($value = '')
```

```
    {
```

```
        $posts = Post::latest()->get();
```

```
      
```

```
        return response()->view('sitemap', [
```

```
            'posts' => $posts
```

```
        ])->header('Content-Type', 'text/xml');
```

```
    }
```

```
}
```

```
​
```

### Create Template File

Create a file **sitemap.blade.php** inside /resources/views folder.

Open file and write this code into it.

sitemap.blade.php

```
<?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('/') }}/post/{{ $post->slug }}</loc>
```

```
<lastmod>{{ $post->created_at->tz('UTC')->toAtomString() }}</lastmod>
```

```
<changefreq>daily</changefreq>
```

```
<priority>0.8</priority>
```

```
</url>
```

```
@endforeach
```

```
</urlset>
```

```
  
```

Above is the structure which will be used and generates a dynamic sitemap.xml file.

### Add Route

Open **web.php** file from /routes folder. Add this route into it.

web.php

```
//...
```

```
​
```

```
use App\Http\Controllers\SitemapController;
```

```
​
```

```
Route::get('sitemap.xml', [SitemapController::class, 'index']);
```

```
​
```

```
//...
```

```
​
```

### Application Testing

Open project to terminal and type the command to start development server

```
$ php artisan serve
```

**URL:** http://127.0.0.1:8000/sitemap.xml

![](https://onlinewebtutorblog.com/wp-content/uploads/2022/06/generate-sitemap-in-laravel-9-tutorial-1024x458.png?ezimgfmt=rs:725x324/rscb5/ng:webp/ngcb5)

We hope this article helped you to learn about Laravel 9 How To Generate Dynamic Sitemap Tutorial in a very detailed way.

[Buy Me a Coffee](https://www.buymeacoffee.com/onlinewebtutor)

Online Web Tutor invites you to try [**Skillshare**](https://www.skillshare.com/r/user/onlinewebtutor?gr_tch_ref=on) free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click [**here**](https://www.skillshare.com/r/user/onlinewebtutor?gr_tch_ref=on) to join.

If you liked this article, then please subscribe to our [**YouTube Channel**](https://www.youtube.com/onlinewebtutor?sub_confirmation=1) for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on [**Twitter**](https://twitter.com/owthub) and [**Facebook**](https://www.facebook.com/owthub).
