Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Feed Laravel Package

laravelium/feed

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Install the package**:
   ```bash
   composer require rumenx/php-feed
  1. Publish the config (optional, but recommended for customization):
    php artisan vendor:publish --provider="RumenDamyanov\Feed\FeedServiceProvider" --tag="config"
    
  2. Define a feed item class (extend RumenDamyanov\Feed\FeedItem):
    namespace App\Feeds;
    
    use RumenDamyanov\Feed\FeedItem;
    
    class BlogPostItem extends FeedItem
    {
        public function __construct(
            public string $title,
            public string $description,
            public string $url,
            public string $date,
            public string $author
        ) {}
    }
    
  3. Generate a basic feed (e.g., in a controller or service):
    use RumenDamyanov\Feed\Feed;
    use App\Feeds\BlogPostItem;
    
    $feed = new Feed('RSS', 'https://example.com/feed');
    $feed->addItem(new BlogPostItem(
        'Post Title',
        'Post description...',
        'https://example.com/post',
        now()->toAtomString(),
        'Author Name'
    ));
    return $feed->render();
    

First Use Case: Blog RSS Feed

  • Use the Feed class to create an RSS/Atom feed for blog posts.
  • Fetch posts from a database (e.g., Eloquent models) and map them to FeedItem objects.
  • Return the rendered feed in a route or controller:
    Route::get('/feed', function () {
        $posts = Post::latest()->take(10)->get();
        $feed = new Feed('RSS', url('/feed'));
        $feed->setTitle('My Blog');
        $feed->setDescription('Latest blog posts');
    
        foreach ($posts as $post) {
            $feed->addItem(new BlogPostItem(
                $post->title,
                $post->excerpt,
                route('posts.show', $post),
                $post->published_at->toAtomString(),
                $post->author->name
            ));
        }
    
        return $feed->render();
    });
    

Implementation Patterns

Workflows

1. Database-Driven Feeds

  • Pattern: Use Eloquent models to fetch data and map to FeedItem objects.
  • Example:
    $feed = new Feed('Atom', url('/feed'));
    $feed->setTitle('Product Updates');
    
    foreach (ProductRelease::published()->get() as $release) {
        $feed->addItem(new ProductReleaseItem(
            $release->title,
            $release->summary,
            route('releases.show', $release),
            $release->released_at->toAtomString(),
            'Team Name'
        ));
    }
    

2. Caching Feeds

  • Pattern: Leverage Laravel's cache to avoid regenerating feeds on every request.
  • Steps:
    1. Configure caching in config/feed.php:
      'cache' => [
          'driver' => 'file', // or 'database', 'redis', etc.
          'prefix' => 'feed_',
          'ttl' => 3600, // Cache for 1 hour
      ],
      
    2. Use the Feed class with caching enabled:
      $feed = new Feed('RSS', url('/feed'), [
          'cache' => true,
      ]);
      

3. Custom Views/Templates

  • Pattern: Override default templates for full control over feed structure.
  • Steps:
    1. Publish the views:
      php artisan vendor:publish --provider="RumenDamyanov\Feed\FeedServiceProvider" --tag="views"
      
    2. Modify resources/views/vendor/feed/rss.blade.php or atom.blade.php.
    3. Pass custom data via FeedItem properties or use setViewData():
      $feed->setViewData(['custom_key' => 'custom_value']);
      

4. Dependency Injection (Laravel)

  • Pattern: Bind the Feed class to the container for easier testing and reuse.
  • Example:
    // In a service provider
    $this->app->bind(Feed::class, function ($app) {
        return new Feed('RSS', url('/feed'));
    });
    
    // In a controller
    public function __construct(private Feed $feed) {}
    
    public function showFeed() {
        $this->feed->addItem(...);
        return $this->feed->render();
    }
    

5. Dynamic Feed Generation

  • Pattern: Generate feeds dynamically based on query parameters (e.g., category filters).
  • Example:
    $category = request('category', 'all');
    $feed = new Feed('Atom', url('/feed'), [
        'title' => "Category: $category",
    ]);
    
    if ($category === 'all') {
        $items = Post::latest()->take(10)->get();
    } else {
        $items = Post::where('category', $category)->latest()->take(10)->get();
    }
    
    foreach ($items as $item) { ... }
    

Integration Tips

  • Laravel Routes: Use named routes for URLs in feed items:
    $feed->addItem(new FeedItem(
        'Post Title',
        'Description',
        route('posts.show', $post), // Dynamic URL
        $post->published_at->toAtomString(),
        $post->author->name
    ));
    
  • Blade Templates: Embed feeds in Blade views for dynamic content:
    $feed = new Feed('RSS', url('/feed'));
    return view('feed', ['feed' => $feed->render()]);
    
  • Testing: Mock FeedItem objects in unit tests:
    $mockItem = Mockery::mock(FeedItem::class);
    $mockItem->shouldReceive('toArray')->andReturn([
        'title' => 'Test',
        'description' => 'Test',
        // ...
    ]);
    $feed->addItem($mockItem);
    

Gotchas and Tips

Pitfalls

  1. Date Formatting:

    • Issue: Incorrect date formats may break feed validation (e.g., RSS/Atom parsers).
    • Fix: Always use Carbon instances and chain toAtomString() or toRssString():
      $post->published_at->toAtomString(); // Correct
      // Avoid: $post->published_at->format('Y-m-d') // May not be compatible
      
  2. Caching Quirks:

    • Issue: Cached feeds may not update immediately if the TTL is too long.
    • Fix: Use a shorter TTL for development or implement a cache tagging system (e.g., Cache::tags(['feed'])->put()).
  3. URL Generation:

    • Issue: Hardcoded URLs in feed items may break in production.
    • Fix: Always use Laravel's url() helper or named routes:
      // Bad: 'https://example.com/post'
      // Good: url('posts/1') or route('posts.show', $post)
      
  4. Character Encoding:

    • Issue: Special characters (e.g., &, <, >) in titles/descriptions may break XML.
    • Fix: Use htmlspecialchars() or let the package handle escaping (it does by default).
  5. Feed Item Order:

    • Issue: Items are added in the order they are inserted, which may not match expectations (e.g., newest first).
    • Fix: Sort items before adding them to the feed:
      $sortedPosts = Post::latest()->get();
      foreach ($sortedPosts as $post) { ... }
      

Debugging

  1. Validate Feed Output:

    • Use online validators like FeedValidator.org to check for errors.
    • Enable Laravel's debug mode to catch exceptions:
      $feed->render(); // Throws exceptions for invalid data
      
  2. Check Cache Storage:

    • If feeds aren't updating, verify the cache driver and TTL:
      php artisan cache:clear
      
    • Inspect cached files (if using file driver):
      ls storage/framework/cache/
      
  3. Template Overrides:

    • Issue: Custom views aren't being used.
    • Fix: Ensure the view file exists in resources/views/vendor/feed/ and the filename matches exactly (e.g., rss.blade.php for RSS).

Extension Points

  1. Custom FeedItem Properties:
    • Extend FeedItem to add custom properties and logic:
      class CustomFeedItem extends FeedItem
      {
          public function __construct(
              public string $title,
              public string $description,
              public string $url,
              public string $date,
              public string $
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
croct/coding-standard
croct/plug-php
nqxcode/phpmorphy
boundwize/pyrameter
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php