DEV Community

Cover image for Create your own simple RSS feed for your blog in a Laravel application
Cuong Giang
Cuong Giang

Posted on

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

Facing to a problem, people often find some packages, install and use it even when the problem is simple, and those packages are too overkill.

I always prefer solving a problem by a "vanilla way" first. And in this case, it's really simple.

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 feeds content in:

<?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>

Change the content on your demand. And enjoy your result!

Oldest comments (0)