I want to generate Dynamic sitemap for my laravel project. I had already searched in so many sites for an answer. some of them describes it using composer. I di
Add this line to your routes.php
Route::get('/sitemap', function()
{
return Response::view('sitemap')->header('Content-Type', 'application/xml');
});
Create new file app\Http\Middleware\sitemap.php
auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
if ( !$request->is("sitemap") && $request->fullUrl() != '' && $this->auth->guest() )
{
$aSiteMap = \Cache::get('sitemap', []);
$changefreq = 'always';
if ( !empty( $aSiteMap[$request->fullUrl()]['added'] ) ) {
$aDateDiff = Carbon::createFromTimestamp( $aSiteMap[$request->fullUrl()]['added'] )->diff( Carbon::now() );
if ( $aDateDiff->y > 0 ) {
$changefreq = 'yearly';
} else if ( $aDateDiff->m > 0) {
$changefreq = 'monthly';
} else if ( $aDateDiff->d > 6 ) {
$changefreq = 'weekly';
} else if ( $aDateDiff->d > 0 && $aDateDiff->d < 7 ) {
$changefreq = 'daily';
} else if ( $aDateDiff->h > 0 ) {
$changefreq = 'hourly';
} else {
$changefreq = 'always';
}
}
$aSiteMap[$request->fullUrl()] = [
'added' => time(),
'lastmod' => Carbon::now()->toIso8601String(),
'priority' => 1 - substr_count($request->getPathInfo(), '/') / 10,
'changefreq' => $changefreq
];
\Cache::put('sitemap', $aSiteMap, 2880);
}
return $next($request);
}
}
And create new view file resources\views\sitemap.blade.php
@foreach( Cache::get('sitemap') as $url => $params )
{{$url}}
{{$params['lastmod']}}
{{$params['changefreq']}}
{{$params['priority']}}
@endforeach
Add an entry to protected $middleware array in the file app\Http\Kernel.php
'sitemap' => 'App\Http\Middleware\sitemap'