Laravel 9 How To Create RSS Feed Tutorial

Reading Time: 6 minutes
1,447 Views

Inside this article we will see the concept i.e Laravel 9 How To create RSS Feed Tutorial. Article is very interesting to learn and also easy to implement into your programming. Article contains the classified information about create RSS feed in laravel 9.

An RSS (Really Simple Syndication) feed is an online file that contains details about every piece of content a site has published.

We will consider some fake posts and create a RSS Feed for those posts. This is a step by step tutorial which creates a RSS feed in laravel 9.

Learn More –

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=root

Create Model & Migration

Open project into terminal.

Let’s create model and migration by using a single command.

Creating model and migration …

$ php artisan make:model Post -m

Above command will create 2 files –

  • Model file with name Post.php inside /app/Models folder.
  • Migration File with name 2022_07_15_040518_create_posts_table.php inside /database/migrations folder.

Open up the migration file and write this code snippet

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('slug');
            $table->text('body');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
};

Open model file Post.php and write this code into it.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    protected $fillable = [
        'title', 'slug', 'body'
    ];
}

Run Migration

Back to terminal and run this command to run migration file.

$ php artisan migrate

It will run all pending migrations of your application. posts table will be created.

Generate Fake Data

We will use the concept of laravel factory to create fake rows into posts table. Back to project terminal and run this command –

$ php artisan make:factory PostFactory

It will create PostFactory.php file inside /database/factories folder. Open file and write this code into it.

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use Str;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Post>
 */
class PostFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition()
    {
        return [
            'title' => $this->faker->text(),
            'slug' => Str::slug($this->faker->text()),
            'body' => $this->faker->paragraph()
        ];
    }
}

Next,

We will use the concept of Tinker to generate fake rows by using PostFactory file.

$ php artisan tinker

>>> App\Models\Post::factory()->count(30)->create();

After seeding test data you will get data something like this –

Create Controller

Back to project terminal and run this command to create controller file.

$ php artisan make:controller RSSFeedController

It will create RSSFeedController.php file inside /app/Http/Controllers folder.

<?php

namespace App\Http\Controllers;

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

class RSSFeedController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $posts = Post::latest()->get();

        return response()->view('rss', [
            'posts' => $posts
        ])->header('Content-Type', 'text/xml');
    }
}

Create Blade Template

Create rss.blade.php file inside /resources/views folder.

Open rss.blade.php and write this complete code into it.

<?=
'<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL ?>
<rss version="2.0">
    <channel>
        <title><![CDATA[ onlinewebtutorblog.com ]]></title>
        <link><![CDATA[ https://your-website.com/feed ]]></link>
        <description><![CDATA[ Best Blog for Programming Articles ]]></description>
        <language>en</language>
        <pubDate>{{ now() }}</pubDate>
  
        @foreach ($posts as $post)
            <item>
                <title><![CDATA[{{ $post->title }}]]></title>
                <link>{{ $post->slug }}</link>
                <description><![CDATA[{!! $post->body !!}]]></description>
                <category>{{ $post->category }}</category>
                <author><![CDATA[Sanjay Kumar]]></author>
                <guid>{{ $post->id }}</guid>
                <pubDate>{{ $post->created_at->toRssString() }}</pubDate>
            </item>
        @endforeach
    </channel>
</rss>

Add Route

Open web.php file from /routes folder. Add this given route into it.

//..

use App\Http\Controllers\RSSFeedController;

Route::get('feed', [RSSFeedController::class, 'index']);

//..

Application Testing

Run this command into project terminal to start development server,

php artisan serve

URL: http://127.0.0.1:8000/feed

We hope this article helped you to learn about Laravel 9 How To Create RSS Feed Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.