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

Open Graph Bundle Laravel Package

abdellahramadan/open-graph-bundle

Symfony bundle for generating Open Graph meta tags. Install via Composer, enable the bundle, then use provided docs and examples to add OG tags to your pages for better social sharing previews.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require abdellahramadan/open-graph-bundle
    

    For non-Flex projects, also register the bundle in config/bundles.php:

    Abdellahramadan\OpenGraph\OpenGraphBundle::class => ['all' => true],
    
  2. First Use Case: Inject the OpenGraphService into a controller or service:

    use Abdellahramadan\OpenGraph\Service\OpenGraphService;
    
    class MyController extends AbstractController
    {
        public function __construct(private OpenGraphService $openGraph)
        {
        }
    
        public function show(Post $post)
        {
            $this->openGraph->setTitle($post->title)
                           ->setDescription($post->excerpt)
                           ->setImage($post->featuredImageUrl)
                           ->setUrl(route('posts.show', $post));
    
            return $this->render('post/show.html.twig');
        }
    }
    
  3. Where to Look First:

    • Twig Integration: The bundle auto-renders Open Graph tags in <head> via Twig’s open_graph block.
    • Configuration: Check config/packages/abdellahramadan_open_graph.yaml for defaults (e.g., site name, default image).

Implementation Patterns

Common Workflows

  1. Dynamic Metadata: Use the fluent interface in controllers/services to set per-page metadata:

    $this->openGraph
        ->setType('article')
        ->setAuthor('Jane Doe')
        ->addProperty('article:published_time', $post->publishedAt->format('c'));
    
  2. Reusable Services: Create a dedicated service to encapsulate Open Graph logic:

    class PostOpenGraphService
    {
        public function __construct(private OpenGraphService $openGraph) {}
    
        public function generateFor(Post $post): void
        {
            $this->openGraph->reset()
                ->setTitle($post->title)
                ->setImage($post->getOgImageUrl())
                ->setUrl(route('posts.show', $post));
        }
    }
    
  3. Twig Integration: Override defaults in templates:

    {% block open_graph %}
        {{ parent() }}
        <meta property="og:locale" content="en_US" />
    {% endblock %}
    
  4. Event-Driven Updates: Listen to kernel events (e.g., KernelEvents::VIEW) to auto-generate metadata:

    public function onKernelView(ViewEvent $event): void
    {
        $post = $event->getControllerResult();
        if ($post instanceof Post) {
            $this->openGraph->generateFor($post);
        }
    }
    
  5. API Responses: Use the OpenGraphService to generate metadata for API responses (e.g., JSON-LD):

    return response()->json([
        'data' => $post,
        'meta' => $this->openGraph->toArray(), // Converts to associative array
    ]);
    

Gotchas and Tips

Pitfalls

  1. Caching Headers:

    • The bundle doesn’t cache metadata by default. Ensure your HTTP cache (e.g., Varnish, Symfony Cache) respects Cache-Control headers for dynamic pages.
    • Fix: Add Cache-Control: no-cache to responses where metadata changes frequently.
  2. Image Validation:

    • The setImage() method doesn’t validate URLs. Broken images can break OG rendering.
    • Fix: Use a validator or middleware:
      if (!filter_var($post->featuredImageUrl, FILTER_VALIDATE_URL)) {
          throw new \InvalidArgumentException('Invalid image URL');
      }
      
  3. Twig Block Conflicts:

    • Overriding open_graph block may break if the parent template doesn’t call parent().
    • Fix: Always include {{ parent() }} to preserve default tags.
  4. Type-Specific Properties:

    • Forgetting og:type (e.g., website, article) can cause social media parsers to ignore metadata.
    • Tip: Use a default type in config:
      abdellahramadan_open_graph:
          default_type: 'article'
      
  5. URL Canonicalization:

    • Social media crawlers may not resolve relative URLs. Always use absolute URLs:
      $this->openGraph->setUrl(url()->current()); // Symfony helper
      

Debugging

  • Validate Output: Use Facebook Sharing Debugger or Twitter Card Validator.
  • Log Missing Tags: Add a subscriber to log unset properties:
    public function onKernelRequest(RequestEvent $event): void
    {
        $tags = $this->openGraph->toArray();
        if (empty($tags['og:title'])) {
            $this->logger->warning('Missing OG title');
        }
    }
    

Extension Points

  1. Custom Properties: Extend the service to support custom OG properties:

    $this->openGraph->addProperty('custom:key', 'value');
    
  2. Multiple Contexts: Use dependency injection to manage separate instances (e.g., for admin vs. public):

    services:
        app.open_graph.admin:
            class: Abdellahramadan\OpenGraph\Service\OpenGraphService
            tags: ['abdellahramadan_open_graph.service']
    
  3. Event Dispatching: Dispatch events when metadata is generated (e.g., for analytics):

    $this->openGraph->onGenerate(function (array $tags) {
        $this->eventDispatcher->dispatch(new OpenGraphGeneratedEvent($tags));
    });
    
  4. Fallback Values: Configure fallbacks in config/packages/abdellahramadan_open_graph.yaml:

    abdellahramadan_open_graph:
        default:
            title: 'Default Title'
            image: '%kernel.project_dir%/public/images/default-og.png'
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware