How to Create a Dynamic Sitemap in Laravel 8

How to Create a Dynamic Sitemap in Laravel 8

Admin
Admin・ 24 Agustus 2021
4 min read ・ 8130 views

Sitemap Laravel - A sitemap is a file that is 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 article, 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. Ok we will start the experiment by installing a new laravel project and so on.

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.

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

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

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

5. Open the file 2021_01_05_012027_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');
    }
}

5. Run the php artisan migrate command to create a table or migrate the migration file in the database>migration folder to the phpMyAdmin database.

6. Create a factory file to create dummy data with the command php artisan make:factory PostFactory -m Post

7. 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) 
        ];
    }
}

insert data sitemap dengan tinker di laravel

8. 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.

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

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

11. 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'));
});

12. 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

sitemap dinamis dengan laravel

The image above is a view of the sitemap.xml file that has been successfully created using the package from spatie.

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

Tinggalkan Komentar
Loading Comments