paint-brush
How to fetch Open Graph metadata in Laravelby@contactmespg
7,262 reads
7,262 reads

How to fetch Open Graph metadata in Laravel

by Shashi Prakash GautamNovember 23rd, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

<strong>What is Open Graph protocol?</strong>

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - How to fetch Open Graph metadata in Laravel
Shashi Prakash Gautam HackerNoon profile picture

Before we begin, let’s first talk about Open Graph protocol.

What is Open Graph protocol?

The Open Graph protocol enables any web page to become a rich object in a social graph. For instance, this is used on Facebook to allow any web page to have the same functionality as any other object on Facebook. You can read more about it here.

Great!!! So how to use it?

Let's say you want something like if a user post message with a link on it. The script will get the URL then get data of it. Its like when you post on facebook. When you paste a link to make a post facebook gets the data feeds of that URL. Something like this.

Now let’s start with how to fetch the Open Graph data of a URL in Laravel.

Install the OpenGraph package for Laravel. OpenGraph is a Laravel package to fetch Open Graph metadata of a URL.

https://github.com/shweshi/OpenGraph.git

Install OpenGraph using composer

composer require "shweshi/opengraph"

If you do not run Laravel 5.5 (or higher), then add the service provider in config/app.php:

Open config/app.php and add shweshi\OpenGraph\Providers\OpenGraphProvider::class, to the end of providers array:

'providers' => array(    ....    shweshi\OpenGraph\Providers\OpenGraphProvider::class,),

Next under the aliases array:

'aliases' => array(    ....    'OpenGraph' => shweshi\OpenGraph\Facades\OpenGraphFacade::class),

If you do run the package on Laravel 5.5+, package auto-discovery takes care of the magic of adding the service provider.

Open routes.php and create a route and use OpenGraph to fetch the OG data of the URL.

Created using https://carbon.now.sh

Now let’s test the route using Postman.

Postman screenshot.

As you can see OpenGraph will give you the OG metadata of the URL.











{"title": "Open Graph protocol","type": "website","url": "http://ogp.me/","image": "http://ogp.me/logo.png","image:type": "image/png","image:width": "300","image:height": "300","image:alt": "The Open Graph logo","description": "The Open Graph protocol enables any web page to become a rich object in a social graph."}

That you can use.

Thanks for reading. If you have some feedback, please reach out to me on Twitter or Github.