Skip to content

Instantly share code, notes, and snippets.

@skadimoolam
Last active November 15, 2018 10:48
Show Gist options
  • Save skadimoolam/789d44a628109a2e89b5d75cb08f595b to your computer and use it in GitHub Desktop.
Save skadimoolam/789d44a628109a2e89b5d75cb08f595b to your computer and use it in GitHub Desktop.
Code snippets for Laravel RSS feed article - https://simplestweb.in/blog/adding-rss-feed-to-your-blog
<?php
use Illuminate\Support\Facades\Storage;
use App\Models\Post;
Artisan::command('generate:feed', function () {
$this->info("Generating RSS Feed");
// It is important that you sort by the latest post
$posts = Post::where('published', true)->latest()->get();
$site = [
'name' => 'YOUR SITE NAME', // Simplest Web
'url' => 'YOUR SITE URL', // Link to your rss.xml. eg. https://simplestweb.in/rss.xml
'description' => 'YOUR SITE DESCRIPTION',
'language' => 'YOUR SITE LANGUAGE', // eg. en, en-IN, jp
'lastBuildDate' => $posts[0]->created_at->format(DateTime::RSS), // This generates the latest posts date in RSS compatible format
];
// Passes posts and site data into the rss.blade.view, out comes text in rss format
$rssFileContents = view('rss', compact('posts', 'site'));
// Saves the generated rss feed into a file called rss.xml in the public folder, this works only
Storage::disk('local')->put('rss.xml', $rssFileContents);
$this->info("Completed");
});
<!-- Change the title and href to your site -->
<link rel="alternate" type="application/rss+xml" title="Simplest Web" href="https://simplestweb.in/rss.xml" />
{!! '<'.'?'.'xml version="1.0" encoding="UTF-8" ?>' !!}
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:media="http://search.yahoo.com/mrss/">
<channel>
<title>{{ $site['name'] }}</title>
<link>{{ $site['url'] }}</link>
<description><![CDATA[{{ $site['description'] }}]]></description>
<atom:link href="{{ $site['url'] }}" rel="self" type="application/rss+xml" />
<language>{{ $site['language'] }}</language>
<lastBuildDate>{{ $site['lastBuildDate'] }}</lastBuildDate>
@foreach($posts as $post)
<item>
<title><![CDATA[{!! $post->title !!}]]></title>
<link>{{ route('pages.post', $post->slug) }}</link>
<guid isPermaLink="true">{{ route('pages.post', $post->slug) }}</guid>
<description><![CDATA[{!! $post->description !!}]]></description>
<content:encoded><![CDATA[{!! $post->content !!}]]></content:encoded>
<dc:creator xmlns:dc="http://purl.org/dc/elements/1.1/">{{ $post->author }}</dc:creator>
<pubDate>{{ $post->created_at->format(DateTime::RSS) }}</pubDate>
</item>
@endforeach
</channel>
</rss>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment