Home » Laravel 9 Automatically Generates Sitemap With Example

Laravel 9 Automatically Generates Sitemap With Example

Last updated on June 4, 2022 by

In this article, we will see that Laravel 9 automatically generates a sitemap with an example. Throughout this post, we will automatically generate a sitemap.xml URL with the help of Laravel 9. Before diving in, we would like to teach you why sitemap is important for your website.

Table of Contents
1. Types Of Sitemaps
2. Use Of Sitemap
3. Best Sitemap Examples
4. Laravel 9 Automatically Generates Sitemap Example

Types Of Sitemaps

There are two types of sitemaps XML and HTML.

  1. HTML sitemap is used to guide the visitors/users to the site. The sitemaps include every page on the website – from the main pages to lower-level pages and can be thought of as a well-organized table of content. An HTML sitemap is just a clickable list of pages on a website.
  2. An XML sitemap is used to guide the search engines to ensure that they find a site’s URLs to index. This will help to improve your search engine optimization (SEO).

Use Of Sitemap

An XML sitemap is a file that lists a website’s important pages, making sure search engines like Google, Bing, Yahoo, etc. can find and crawl them all. It also helps search engines understand your website structure.

You want search engines to crawl every essential page of your website. But sometimes, pages end up without any internal links pointing to them, making them hard to find. A sitemap can help speed up content discovery.

Read more about sitemap from here.

Best Sitemap Examples

Here is the very basic XML sitemap example suggested by Google.

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>http://www.example.com/foo.html</loc>
    <lastmod>2018-06-04</lastmod>
  </url>
</urlset>

The Sitemap must:

  1. Begin with an opening <urlset> tag and end with a closing </urlset> tag.
  2. Specify the namespace (protocol standard) within the <urlset> tag.
  3. Include a <url> entry for each URL, as a parent XML tag.
  4. Include a <loc> child entry for each <url> parent tag.

Laravel 9 Automatically Generates Sitemap Example

In this example, we will create a posts table for our blog Laravel 9 application. In the posts table, we will add the id, title, slug, description, etc. columns.

Then we will generate some dummy data using the Laravel Factories and after that, we will fetch all the data from posts and generate the XML file. Let’s see how to do it.

Step 1: Install Laravel 9

If you already have installed Laravel 9 on your local machine, you can skip this step. You can easily install the fresh version of Laravel 9 by running the below command in your terminal. You can give it any name but in this case, we will name it demo-app.

composer create-project --prefer-dist laravel/laravel demo-app

or use the following command to install the specific Laravel version

composer create-project laravel/laravel:^9.0 demo_app

Notes: To install Laravel 9 you need PHP 8.0. So make sure you have installed PHP 8.0 in your local WAMP, LAMP, MAMP, etc.

Step 2: Database Configuration

In this step, we will add the database credentials to the .env file. We need to add the database Name, database Host, MySQL username, and password. So let’s open the .env file and add all the details below as per your setup.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=add-your-database-name(demo-app)
DB_USERNAME=add-your-database-username(root)
DB_PASSWORD=add-your-database-password(may be blank)

Step 3: Create Migration

Now, we will create a posts table using the Laravel migrations. Let’s run the below command to create a migration.

cd demo-app
php artisan make:migration create_posts_table --create=posts

After running the above command a new migration file will be created in “database/migrations” directory.

database/migrations/2022_06_03_20000_create_posts_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('slug');
            $table->longText('description')->nullable();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Now, run the below command to create database tables.

php artisan migrate

Step 4: Create A Model

In this step, we will create a Product model which helps us to connect with the products table so that we can perform the database operations using the model. Run the below command to create a model.

php artisan make:model Post

Then the new file will be created in demo-app/app/Models/Post.php. In the model add the title, slug, and description fields in the fillable array.

app/Models/Post.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', 'description'
    ];
}

Step 5: Generate Dummy Data

If you already have data in your database then just skip this step. In this step, we will create a post factory and generate dummy data to create a sitemap in Laravel 9. Let’s run the below command to create a factory.

php artisan make:factory PostFactory

After running the above command a new file will be created in database/factories/PostFactory.php. Let’s open it and add the following code to it.

database/factories/PostFactory.php

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use App\Models\Post;
use Illuminate\Support\Str;

class PostFactory extends Factory
{
    protected $model = Post::class;

    public function definition()
    {
        return [
            'title' => $this->faker->text(),
            'slug' => Str::slug($this->faker->text()),
            'description' => $this->faker->paragraph()
        ];
    }
}

Run the below command to open the tinker shell.

php artisan tinker

Tinker shell will start with >>> as shown below, now run the below command to generate dummy data in Laravel.

Psy Shell v0.11.4 (PHP 7.4.9 — cli) by Justin Hileman

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

Step 6: Create Routes

We need to add routes in routes/web.php file to generate the Laravel 9 sitemap. We need only GET route which is used to generate and show the sitemap.xml in Laravel. Let’s add it.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\SitemapController;

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

Step 7: Create SitemapController

Let’s create a SitemapController with index() method. To create a controller run the below command:

php artisan make:controller SitemapController

After running the above command a new file will be created in the Controllers directory. Let’s open it and add the following code:

app/Http/Controllers/SitemapController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;

class SitemapController extends Controller
{
    public function index()
    {
        $posts = Post::latest()->get();

        return response()->view('sitemap', [
            'posts' => $posts
        ])->header('Content-Type', 'text/xml');
    }
}

Step 8: Create Blade/HTML File

At last, we need to create a view blade file in the views folder to generate the Laravel 9 sitemap with an example. Let’s create below blade file.

resources/views/sitemap.blade.php

<?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>

Step 9: Output – Automatically Generate Laravel 9 Sitemap

Hurray! We have completed all steps to automatically generate the Laravel 9 sitemap tutorial with an example. Let’s run the below command and see how it’s working.

php artisan serve

After running the above command, open your browser and visit the site below URL:

http://localhost:8000/sitemap.xml

Additionally, read our guide:

  1. Laravel 9 Image Upload Tutorial With Example
  2. Laravel 9 Multiple Database Connections Example
  3. Laravel: Change Column Type In Migration
  4. Laravel: Change Column Name In Migration
  5. How To Use Where Date Between In Laravel
  6. How To Add Laravel Next Prev Pagination
  7. Laravel Remove Column From Table In Migration
  8. Laravel: Get Month Name From Date
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Update Pivot Table In Laravel
  11. How To Install Vue In Laravel 8 Step By Step
  12. How To Handle Failed Jobs In Laravel
  13. Best Ways To Define Global Variable In Laravel
  14. How To Get Latest Records In Laravel
  15. Laravel Twilio Send SMS Tutorial With Example
  16. How To Pass Laravel URL Parameter
  17. Set Default Value Of Timestamp In Laravel Migration
  18. Laravel 9 File Upload Tutorial With Example
  19. How To Schedule Tasks In Laravel With Example
  20. Laravel Collection Push() And Put() With Example

That’s it from our end. We hope this article helped you to automatically generate the Laravel 9 sitemap tutorial with the example.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post 🙂 Keep Smiling! Happy Coding!

 
 

Leave a Comment