Creating And Retrieving Open Graph Images

Generating Open Graph Images

If the model preparation is done correctly, an OG Image will be created when a new record is created.

Manually Triggering OG Image Generation

To manually trigger OG Image generation, you can call generateGraphify() method on your model instance as below.

$yourModel->generateGraphify();

If your model does not have a slug then the generated images will not have any filename, therefore ther will only be one .png image in your storage directory. To avoid this you will need to override the getGraphifyFileName method in your model. Read Customizating file name for more information.

Note: Default OG image generation view expects your model to have title and author_name. If these are not in your model, the generated OG image may look empty. You can easily fix this by declaring an accessor (get attribute for title and/or author_name).

Retrieving OG Images

To retrieve a generated OG image, you can use the below method.

$yourModel->graphify_image;

Adding A Fallback OG Image

Sometimes things just do not go the way you want. So having a fallback OG Image when there is none available is a good thing to have. To define your fallback image, add the below method to your model and update the return value however you like.

public function placeholderOgImage(): Attribute
{
    return Attribute::make(
        get: fn () => '' // Your fallback image goes here
    );
}

Displaying OG Images

You can add the generated OG images to your header using the below tags

<meta property="og:image" content="{{ $post->graphify_image }}">
<meta name="twitter:image" content="{{ $post->graphify_image }}">

Last updated