Laravel 生成 sitemap.xml

文章目录

    从 Google Search Console 看,通过 sitemap.xml 提交的 URL 只有 183 个,而当前博客实际上已经有近 600 篇。而这个 sitemap 是很旧之前上一版 gitbook 生成的。

    虽然这些 URL 实际上已经被索引了,但我仍然想规范一下,重新生成 sitemap.xml。

    对比了一下几个 Laravel Sitemap 的实现,感觉还是

    https://github.com/Laravelium/laravel-sitemap

    比较简单明了。

    public function sitemap(Request $request) {
    	// create new sitemap object
    	$sitemap = App::make("sitemap");
    	$sitemap->setCache('laravel.sitemap', 60);
    
    	// get all posts from db
    	$posts = DB::table('articles')
    		->where('publish', 1)
    		->orderBy('id', 'desc')
    		->get();
    
    	// add every post to the sitemap
    	foreach ($posts as $post) {
    		$sitemap->add("https://www.sunzhongwei.com/".$post->slug, $post->created_at, 0.9, 'monthly');
    	}
    
    	return $sitemap->render('xml');
    }
    

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式