In another article, I decribed how I rebuilt my site with Laravel in a day. Though the website took shape within a day's work, I still had many essential features to include, such as RSS feeds, blog post comments, and structured data, to name a few. I wanted to explain my solution for implementing an RSS feed. This may be a simple solution but the point is that it works like a charm. So let's get started building an RSS feed for your site.

TLDR;

Here's the gist of my solution.

Create a view file in theresourcesfolder. This file will have the XML structure which can be populated dynamically.

Create an Artisan command called generate:feedin the routes/console.php file.

This command fetches all the posts and sends them to the RSS view. Then writes the returned XML formatted data to a file named rss.xml in the public folder.

I am sure you understood none of the above instructions, so let me explain this in a bit more detail.

The RSS View

Create a file in your resources/viewsfolder, I called it rss.blade.php. Paste in the code shown below. I'll explain as we go.

As you might notice, we pass two variables to this view, $siteand $posts. The first one contains some information about the your site. The second one contains an array of posts you want to include in this feed.

Next, we will create the Artisan command.

The Artisan Command

You may ask why we need to write all the logic in a command instead of a controller. I have a few reasons why I chose this method.

I may want to call this command from the terminal.

I may also call it from a controller.

Since this command generates a file in the public folder there's no need for requests to go through Laravel.

This is pretty basic stuff, so you should be able to recognize what the code does. First, we create an Artisan command. Then we fetch all the posts sorted by the most recent ones. Next, we create an array with our site details. Then we pass all this data to our rss.blade.php view file, which returns the formatted XML we need. Lastly, we write this to the rss.xml file in our public folder. That was't too hard, was it?

The above code lets the RSS readers know that there's an RSS feed in this site and points it to the URL.

That's About It

I hope you understood my solution to implementing a RSS Feed for a Laravel site. There's a lot more information you can add to this feed, and you can find more resources below. If you like this tutorial, do let me know. I will write more of them. If you get stuck anywhere in the tutorial, let me know, I'm happy to help. Thanks!