PHP code example of ichinya / laravel-sitemap

1. Go to this page and download the library: Download ichinya/laravel-sitemap library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ichinya / laravel-sitemap example snippets

 


namespace App\Models;

use Ichinya\LaravelSitemap\Sitemapable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model implements Sitemapable
{
    use HasFactory;
}

// маршрут для списка, в примере posts.index
public ?string $sitemap_model_route_list = null;
// маршрут для каждой позиции в примере это posts.show
public ?string $sitemap_model_route_item = null;
 
    public function getSitemapModelRouteItem(): string
    {
        return $this->sitemap_model_route_item;
    }
    
    public function getSitemapModelRouteList(): string
    {
        return $this->sitemap_model_route_list;
    }

    // можно указанть другое поле с отметкой времени, например published_at. Если поле данное поле у позиции будет null, то она не попадет в карту. Данное поведение можно поменять, смотрите ниже 
    public string $sitemap_datetime = 'updated_at';
    
    // можно использовать метод для использования любой логики
    public function getSitemapDatetime(): string
    {
        return $this->sitemap_datetime;
    }

    // тут можно написать просто запрос, какие позиции попадут в карту
    public function getSitemapItems()
    {
        return self::whereNotNull($this->getSitemapDatetime())->get();
    }

Route::get('/sitemaps.xml', [SitemapController::class, 'index']);

 public function index()
    {
        $article = \App\Models\Article::all();

        $sitemapUrsl = new \Ichinya\LaravelSitemap\SitemapUrls();
        // можно указать значения по умолчанию $changefreq = 'weekly', $priority = 0.5
        $sitemapUrsl = new \Ichinya\LaravelSitemap\SitemapUrls('weekly', 0.5);
     
        $sitemapUrsl->addModel($article, 'article.show'); // второй параметр имя роута, с помощью которого генерируютя ссылки
        $sitemapUrsl->addModelClass(\App\Models\Page::class) // имя роута будет page.show
        
        // при добавлении модели можно указать поле с датой следующим параметром.
        $sitemapUrsl->addModelClass(\App\Models\StaticPage::class, 'created_at')
        
        $sitemapUrsl
            ->addUrl(route('main'), time())
            ->addUrl(route('categories.edit', time()) // добавляем ссылки на различные страницы
            ->addUrl('/rules', time(), 'weekly', 0.5); // добавляем ссылки на различные страницы
        // время можно указать в timestamp, через Carbon, объектом DateTime или строкой 


        $sitemap = Sitemap::create($sitemapUrsl); // ядро ссылок собрали, теперь отправляем на создание

        return $sitemap->render();
    }