Currently seeking new career opportunities in web development, particularly with Laravel, Hire Me

Create an XML sitemap

David Carr

Laravel Framework Tutorials PHP & MySQL

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)
        <url>
            <loc>{{ url($post->slug) }}</loc>
            <lastmod>{{ $post->updated_at->tz('GMT')->toAtomString() }}</lastmod>
            <changefreq>weekly</changefreq>
            <priority>0.6</priority>
        </url>
    @endforeach
</urlset>

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'/>

 

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

Help support the blog so that I can continue creating new content!

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Learn Laravel with Laracasts

Faster Laravel Hosting

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.