DEV Community

Cover image for How to Create a Dynamic Sitemap in Laravel 8
Hilmi Hidayat
Hilmi Hidayat

Posted on • Edited on

How to Create a Dynamic Sitemap in Laravel 8

Laravel Dynamic Sitemap - Sitemap is a file used to provide information about pages, videos and other files on a website. Search engines like Google read sitemap files to crawl sites more effectively. Sitemaps tell Google which pages are considered important on a website.

In this post, we will both learn how to create a dynamic sitemap in laravel 8 using the package from spatie.be so that we no longer need to manually update the sitemap using the sitemap generator. Alright we will start the experiment by installing a new laravel project and so on.

Following are the steps:

  1. Install a new laravel 8 project.

To create a laravel project with the latest version of laravel, please open a terminal and go to the directory where you want to install the laravel project. Then install laravel with the command composer create-project laravel/laravel sitemap. With this command we will create a new laravel project with the name project sitemap.

  1. Create a new database in phpMyAdmin with a name of your own (in this experiment, I created a database with the name sitemap).

  2. Match DB_DATABASE with the name of the database you just created in step number 2.

  3. Create Post model and migration files with the command php artisan make:model Post -m.

  4. Open the file [timestamp]_create_posts_table.php or the migration file that was created with the command in step number 4. Edit the script in the file as below.

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable 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->longText('body');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Run the php artisan migrate command to create a table or migrate the migration file in the database>migration folder to the phpMyAdmin database.

  2. Create a factory file to create dummy data with the command php artisan make:factory PostFactory --model=Post

  3. Open the PostFactory file in the database>factory folder, then edit the script in the file to be as below.

<?php
namespace Database\Factories;
use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class PostFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Post::class;
    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        $title = $this->faker->sentence;
        $slug = Str::slug($title);
        return [
            'title' => $title,
            'slug'  => $slug,
            'body'  => $this->faker->paragraph(10) 
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

Laravel dynamic sitemap

  1. Then open the terminal again and run the php artisan tinker command. Then run the command App\Models\Post::factory()->count(10)->create(); to create a dummy data of 10 data.

  2. Install the spatie laravel sitemap package by running the composer require spatie/laravel-sitemap command in the terminal.

  3. Run the command php artisan vendor:publish --provider="Spatie\Sitemap\SitemapServiceProvider" --tag=config to copy the sitemap.php file into the config folder.

  4. Open the web.php file in the routes folder. Then edit the script in the file to be like below.

<?php
use Illuminate\Support\Facades\Route;
use App\Models\Post;
use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
    return view('welcome');
});
Route::get('/sitemap', function(){
    $sitemap = Sitemap::create()
    ->add(Url::create('/about-us'))
    ->add(Url::create('/contact_us'));

    $post = Post::all();
    foreach ($post as $post) {
        $sitemap->add(Url::create("/post/{$post->slug}"));
    }
    $sitemap->writeToFile(public_path('sitemap.xml'));
}); 
Enter fullscreen mode Exit fullscreen mode
  1. Now run php artisan serve then access to the url example.test/sitemap or 127.0.0.1:8000/sitemap then when we check in the public folder there is a new file with the name sitemap.xml Laravel dynamic sitemap The image above is a view of the sitemap.xml file that has been successfully created using the package from spatie.

So this post is about how to create a sitemap.xml file with the package from the spatie laravel sitemap.

Thank's for your attention and don't forget to visit Codelapan.com, to get articles about web programming, web design, and others.

Top comments (0)