Quick Setup
1. Create a Helper Function
app/Helpers/OGImage.php
<?php
namespace App\Helpers;
class OGImage
{
public static function url(array $params): string
{
$baseUrl = 'https://ogimageapi.io/api/generate';
$query = http_build_query([
'title' => $params['title'] ?? '',
'subtitle' => $params['subtitle'] ?? '',
'theme' => $params['theme'] ?? 'dark',
]);
return $baseUrl . '?' . $query;
}
}
2. Use in Blade Templates
resources/views/posts/show.blade.php
@section('meta')
@php
$ogImage = \App\Helpers\OGImage::url([
'title' => $post->title,
'subtitle' => 'By ' . $post->author->name,
'theme' => 'dark'
]);
@endphp
<meta property="og:title" content="{{ $post->title }}">
<meta property="og:description" content="{{ $post->excerpt }}">
<meta property="og:image" content="{{ $ogImage }}">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="{{ $ogImage }}">
@endsection
3. Create a Blade Component
app/View/Components/OGMeta.php
<?php
namespace App\View\Components;
use Illuminate\View\Component;
use App\Helpers\OGImage;
class OGMeta extends Component
{
public string $title;
public string $description;
public string $image;
public function __construct(
string $title,
string $description,
?string $author = null
) {
$this->title = $title;
$this->description = $description;
$this->image = OGImage::url([
'title' => $title,
'subtitle' => $author ?? '',
'theme' => 'dark'
]);
}
public function render()
{
return view('components.og-meta');
}
}
resources/views/components/og-meta.blade.php
<meta property="og:title" content="{{ $title }}">
<meta property="og:description" content="{{ $description }}">
<meta property="og:image" content="{{ $image }}">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="{{ $image }}">
Use it in any view:
<x-og-meta
title="{{ $post->title }}"
description="{{ $post->excerpt }}"
author="{{ $post->author->name }}"
/>