Simple sitemap.xml example in Laravel for SEO
By Konstantin Ippolitov,
1) app/Models/Page.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Page extends Model
{
protected $table = 'pages';
}
?>
2) app/Http/Controllers/SitemapController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Response;
use App\Models\Page;
class SitemapController extends Controller
{
public function index()
{
$entries = Page::select('link', 'updated_at','blog')
->where('work', 1)
->orderBy('updated_at', 'desc')
->get();
$xml = view('pages/sitemap', compact('entries'))->render();
return Response::make($xml, 200, ['Content-Type' => 'application/xml']);
}
}
3) routes/web.php
Route::get('sitemap.xml', 'SitemapController@index');
4) resources/views/pages/sitemap.blade.php
@php
echo '<?xml version="1.0" encoding="UTF-8" ?>';
@endphp
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
@foreach ($entries as $entry)
<url>
@if ($entry->blog == 1)
<loc>{{ url('/') }}/page/{{ $entry->link }}/</loc>
@else
<loc>{{ url($entry->link) }}/</loc>
@endif
<lastmod>{{ $entry->updated_at->tz('UTC')->toAtomString() }}</lastmod>
</url>
@endforeach
</urlset>
5) CREATE TABLE
CREATE TABLE `pages` (
`id` int(5) NOT NULL,
`header` varchar(255) NOT NULL,
`text` mediumtext NOT NULL,
`work` int(11) DEFAULT NULL,
`link` varchar(255) NOT NULL,
`sort` varchar(255) DEFAULT NULL,
`img` varchar(255) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`blog` tinyint(2) NOT NULL DEFAULT 1
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
More details in my GitHub