Blog Detail

20

Sep
Generate Dynamic Open Graph Images for Your Laravel Website cover image

Generate Dynamic Open Graph Images for Your Laravel Website

Laravel Open Graph Images is a fantastic package that enables you to dynamically create Open Graph images for your website. Just add the meta tag with our URL to the head of your page. The package will then generate the image and add it to the page. You can edit the view template which you can find in the resources folder.

Installation

You can install the package via composer:

composer require vormkracht10/laravel-open-graph-image

Then you should install puppeteer:

npm install puppeteer

You should publish the views using:

php artisan vendor:publish --tag="open-graph-image-views"

Usage

Just add this blade component to the head of your page.

<x-open-graph-image::metatags title="Vormkracht10" subtitle="Slimme websites" />

If you don't want to use the blade component you can also use the facade or helper method to generate the URL to the image.

// Facade
use Vormkracht10\LaravelOpenGraphImage\Facades\OpenGraphImage;

OpenGraphImage::url(['title' => 'Vormkracht10', 'subtitle' => 'Slimme websites']);

// Helper 
og(['title' => 'Vormkracht10', 'subtitle' => 'Slimme websites']);

When you share the page on any platform, the image will automatically be generated, cached and then shown in your post.

Passing extra attributes

Want to add more custom attributes to modify the button text for example? Simply pass them down to the blade component, facade, or helper method:

<x-open-graph-image::metatags title="Vormkracht10" subtitle="Slimme websites" button="Lees meer" />
// Facade
use Vormkracht10\LaravelOpenGraphImage\Facades\OpenGraphImage;

OpenGraphImage::url(['title' => 'Vormkracht10', 'subtitle' => 'Slimme websites', 'button' => 'Lees meer']);

// Helper
og(['title' => 'Vormkracht10', 'subtitle' => 'Slimme websites', 'button' => 'Lees meer']);

You can now access the variable in the template.blade.php by using the {{ $button }} variable.

Clearing cached images

All generated open graph images are cached by default. If you want to remove the cache, you can use the following command:

php artisan open-graph-image:clear-cache

For more details and source code, please visit Github.

Published at : 20-09-2022

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch project