Skip to content

Instantly share code, notes, and snippets.

@johnroyer
Last active February 17, 2022 06:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnroyer/745ac3b0a88b2a43d8dac42427f55aa9 to your computer and use it in GitHub Desktop.
Save johnroyer/745ac3b0a88b2a43d8dac42427f55aa9 to your computer and use it in GitHub Desktop.
Sitemap Middleware for Laravel
<?php
/**
* This file is orginzed from @FDisk from StackOverflow
* @see https://stackoverflow.com/a/28608156/8681141
*/
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
class Sitemap
{
const TTL = 86400; // 1 day
const KEY_NAME = 'app_sitemap';
protected $guard;
/**
* @param Guard $guard
*/
public function __construct(Guard $guard)
{
$this->guard = $guard;
}
/**
* @param Request $request
* @param Closure $next
* @return mixed|void
*/
public function handle(Request $request, Closure $next)
{
if (
Cache::has(self::KEY_NAME)
$request->is('sitemap') ||
$request->fullUrl() === '/' ||
!$this->guard->guest()
) {
return $next($request);
}
// update sitemap
$sitemap = Cache::get(self::KEY_NAME, []);
$changeFreq = 'always';
if (!empty($sitemap[$request->fullUrl()]['added'])) {
$aDateDiff = Carbon::createFromTimestamp($sitemap[$request->fullUrl()]['added'])->diff(Carbon::now());
if ($aDateDiff->y > 0) {
$changeFreq = 'yearly';
} elseif ($aDateDiff->m > 0) {
$changeFreq = 'monthly';
} elseif ($aDateDiff->d > 6) {
$changeFreq = 'weekly';
} elseif ($aDateDiff->d > 0 && $aDateDiff->d < 7) {
$changeFreq = 'daily';
} elseif ($aDateDiff->h > 0) {
$changeFreq = 'hourly';
} else {
$changeFreq = 'always';
}
}
$sitemap[$request->fullUrl()] = [
'added' => time(),
'lastmod' => Carbon::now()->toIso8601String(),
'priority' => 1 - substr_count($request->getPathInfo(), '/') / 10,
'changeFreq' => $changeFreq
];
Cache::put(self::KEY_NAME, $sitemap, self::TTL);
return $next($request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment