Black Friday sale is now on! 50% off Laravel: The Modular Way. Learn more

Create an XML sitemap

David Carr

Laravel Framework PHP & MySQL Tutorials

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


    Laravel Modules Book by David Carr

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

    Subscribe to my newsletter

    Subscribe and get my books and product announcements.

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