Create your own simple RSS feed for your blog in a Laravel application

Oct 2021

When faced with a problem, people often tend to search for and install packages, even for simple problems, which can be excessive.

I always prefer to solve a problem using the simplest approach first, the "vanilla way". In this case, it is quite straightforward.

In your routes:

Route::get('/feed', 'FeedController');

In your FeedController:

<?php

namespace App\Http\Controllers;

use App\Post;
use Illuminate\Http\Request;

class FeedController extends Controller
{
    public function __invoke()
    {
        $posts = Post::all();

        $content = view('feed', compact('posts'));

        return response($content, 200)
            ->header('Content-Type', 'text/xml');
    }
}

In your view, feed.blade.php, put the XML feed content:

<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <id>{{ url('/feed') }}</id>
    <link href="{{ url('/feed') }}"></link>
    <title><![CDATA[{{ config('app.name') }}]]></title>
    <description></description>
    <language></language>
    <updated>{{ $posts->first()->updated_at->format('D, d M Y H:i:s +0000') }}</updated>
    @foreach ($posts as $post)
    <entry>
        <title><![CDATA[{{ $post->title }}]]></title>
        <link rel="alternate" href="{{ $post->path() }}" />
        <id>{{ $post->path() }}</id>
        <author>
            <name> <![CDATA[{{ $post->user->name }}]]></name>
        </author>
        <summary type="html">
            <![CDATA[{!! parsedown($post->content) !!}]]>
        </summary>
        <category type="html">
            <![CDATA[]]>
        </category>
        <updated>{{ $post->updated_at->format('D, d M Y H:i:s +0000') }}</updated>
    </entry>
    @endforeach
</feed>

Feel free to customize the content as needed. Enjoy the results!

My Newsletter

I send out an email every so often about cool stuff I'm working on or launching. If you dig, go ahead and sign up!

    Follow the RSS Feed.