Tutorials, PHP & MySQL, Laravel Framework

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="http://www.sitemaps.org/schemas/sitemap/0.9">
    @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'/>


David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.