Laravel Framework | PHP & MySQL | Tutorials

David Carr

Create an XML sitemap

Creating xml sitemaps are great for Google to inform their search bots of all your pages and their urls for them to index, in this post I'll cover how to create an XML sitemap.

First, create a route that will respond with the sitemap

Route::get('sitemap.xml', 'BlogController@sitemap');

Next, create a method to get all records and load a view.

public function sitemap()
    $posts = Post::get();
    return view('sitemap')->with(compact('posts'));

In the view use a Request header to set the content type to be text/xml and also echo out the xml version.

Then set a urlset group and inside of it loop through the records.

Inside the look create a url group tag with these fields:

loc - the url of the page
lastmod - set the date the url was last updated and format the timezone
changefreq - how ofter the content may change
priority - what level or priority to give.

{{ Request::header('Content-Type : text/xml') }}
<?php echo '<?xml version="1.0" encoding="UTF-8"?>';?>

<urlset xmlns="">
    @foreach ($posts as $post)
            <loc>{{ url($post->slug) }}</loc>
            <lastmod>{{ $post->updated_at->tz('GMT')->toAtomString() }}</lastmod>

the last step is to add a sitemap link tag into the head section of the html:

<link href='{{ url('sitemap.xml') }}' rel='alternate' title='Sitemap' type='application/rss+xml'/>


Domains are often purchased from multiple providers, keeping track of where a domain is and its DNS settings can be tricky. Domain Mapper solves this by listing all your domains in one place. View your DNS settings and receive reminders to renew your domains. Try it today.

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2021 DC Blog. All code MIT license. All rights reserved.