ruvelo / laravel-social-cards
Share images for your Laravel pages: one Blade tag adds the Open Graph and X card tags, and a 1200×630 PNG is drawn from a simple template with GD. No headless browser.
Requires
- php: ^8.3
- ext-gd: *
- laravel/framework: ^12.4.1|^13.0
Requires (Dev)
- larastan/larastan: ^3.13
- laravel/pint: ^1.32
- orchestra/testbench: ^10.0|^11.0
- phpunit/phpunit: ^11.5|^12.0
Suggests
- ext-imagick: Draw cards with ImageMagick instead of GD (SOCIAL_CARDS_DRIVER=imagick)
Provides
None
Conflicts
None
Replaces
None
README
Quick start Configuration Upgrading Developer guide Changelog
Laravel Social Cards
The image people see when your pages are shared on social networks and in chats, drawn in PHP from a simple template: no headless browser, no Node, nothing to install.
Quick start
composer require ruvelo/laravel-social-cards
Put one tag in your page's <head>:
<x-social-cards::meta :title="$post->title" :description="$post->excerpt" />
That's it. The page now has its Open Graph and X (Twitter) card tags, and og:image points to a 1200×630 PNG of your title, drawn the first time a network asks for it and served from storage after that. Want to see it without sharing? php artisan social-cards:preview "My first card" writes one to social-card.png.
What you get
- Every tag a share needs:
og:title,og:description,og:imagewith its size and alt text,og:url,og:site_name,twitter:cardas a large image, and the rest. - A clean card for every page, in three built-in templates: simple, image (a photo under a dark overlay) and split (your logo or a photo beside the text). Your colours, logo and font.
- Long titles shrink and wrap to fit, and only as a last resort end with an ellipsis. Emoji and characters the font can't draw are left out, never shown as empty boxes.
- Drawn with GD, which comes with PHP: it runs on shared hosting, in Docker and on small servers. Imagick works too, if you have it.
- Drawn once, then stored on a disk (
publicby default). A changed title gets a new image and a new URL, so networks fetch the new one. - Safe: image URLs are signed by your app, text is cleaned and capped, and nothing is fetched from other servers unless you allow the host.
- Your own templates in a few lines of PHP, and
social-cards:clearto start afresh.
Optional features
Pre-generate on save
Add a trait to a model and its card is drawn when it's saved (on your queue, if you have one), so the first visitor gets a stored file. Details.
Remote images
Use images from your CDN or another host. Off by default: list the hosts in social-cards.images.remote.hosts and set SOCIAL_CARDS_REMOTE_IMAGES=true. Details.
Imagick
Set SOCIAL_CARDS_DRIVER=imagick to draw with ImageMagick when the extension is installed. Same layout, slightly smoother resampling.
The templates
These were drawn by the package itself: composer samples draws them again into art/.
Using it
The tag
<x-social-cards::meta :title="$post->title" :description="$post->excerpt" :image="$post->cover_path" template="image" type="article" />
| Attribute | |
|---|---|
title |
Required (or pass :card or :for) |
description |
Shown on the card and in og:description |
image |
The photo for the image and split templates: a path under public/, a file in storage/app/public, or an allowed URL |
template |
simple, image, split, or one of yours. Default: social-cards.template |
:theme |
Colours for this card only, e.g. :theme="['accent' => $category->colour]" |
:data |
Extra values for your own templates |
type |
og:type. Default website; article for posts |
url |
og:url. Default: the current URL |
site-name |
og:site_name. Default: social-cards.site_name (your APP_NAME) |
alt |
The image's alt text. Default: the title |
:card |
A Card you built in PHP |
:for |
A model that describes its own card (below) |
HTML in titles and descriptions is stripped and entities are decoded, so an excerpt straight from your editor is fine. Text is capped at 200 characters for titles and 300 for descriptions, cut at a word.
Your look
Publish the config (php artisan vendor:publish --tag=social-cards-config) and set your colours, logo and default template:
'template' => 'simple', 'theme' => [ 'background' => '#ffffff', 'text' => '#16162a', 'muted' => '#4b4b63', // descriptions 'accent' => '#3d4eff', // the stripe, the mark and the domain 'accent_alt' => '#a78bfa', // the other end of the gradients 'overlay' => '#11111cd9', // darkens photos in the image template ], 'logo' => 'images/logo.png', // under public/, or an absolute path
The logo can be a PNG, JPEG, GIF or WebP; a square one sits beside your site name, a wide one replaces it. GD can't read SVG, so export a PNG. Without a logo, the cards show your site name's initial on the accent gradient.
Fonts
Inter (regular and semibold) is bundled, under the SIL Open Font License; it covers Latin, Greek and Cyrillic. To use your own, point fonts.regular and fonts.bold at .ttf or .otf files.
Characters none of the fonts can draw, such as emoji, are left out rather than drawn as empty boxes. For Chinese, Japanese, Korean, Arabic and other scripts, add a font that has them as a fallback:
'fonts' => [ 'regular' => null, 'bold' => null, 'fallbacks' => [resource_path('fonts/NotoSansJP-Regular.ttf')], ],
Text is laid out left to right; right-to-left scripts aren't shaped.
Models
Let a model describe its own card, then pass the model to the tag:
use Ruvelo\SocialCards\Card; use Ruvelo\SocialCards\Concerns\GeneratesSocialCard; use Ruvelo\SocialCards\Contracts\HasSocialCard; class Post extends Model implements HasSocialCard { use GeneratesSocialCard; public function toSocialCard(): Card { return Card::make($this->title, $this->excerpt, image: $this->cover_path, template: 'image'); } }
<x-social-cards::meta :for="$post" type="article" />
With GeneratesSocialCard, saving the model draws its card in a GenerateSocialCard job, after the transaction commits: straight away with the sync queue, or in the background with a worker. Choose the queue with pregenerate.connection and pregenerate.queue, or turn it off with SOCIAL_CARDS_PREGENERATE=false. $post->socialCardUrl() gives the image URL, for APIs and front ends that write their own tags.
Images
A card's image can be:
- a path under
public/(images/cover.jpgor/images/cover.jpg), - a file in
storage/app/public, also by itsStorage::url()path (/storage/covers/1.jpg), - a URL on your own app (
asset('images/cover.jpg')), which is read from disk, not over HTTP, - a URL on another host, only if you allow it:
'images' => [ 'remote' => [ 'enabled' => env('SOCIAL_CARDS_REMOTE_IMAGES', false), 'hosts' => ['images.example-cdn.com', '*.cloudfront.net'], ], ],
PNG, JPEG, GIF and WebP up to 5 MB and 25 megapixels. An image that can't be used (missing, too big, not allowed) is left out and the reason is logged: the card is still drawn.
Storing and serving
Cards are stored on social-cards.disk (public) under social-cards/, named after a hash of everything that affects how they look: the text, image, template and its version, colours, logo, fonts and driver. Change any of them and the next request draws a new card; the URL in your tags changes too, so networks that cache images by URL pick up the new one.
By default the PNG is sent from PHP (serve = file), which works with any disk. With serve = redirect, the route redirects to the disk's own URL instead: a public disk after php artisan storage:link, or S3 and a CDN.
php artisan social-cards:clear # delete every stored card; they're drawn again when asked for
php artisan social-cards:clear --days=90 # only those not drawn in the last 90 days
Old cards aren't deleted when a title changes (a network may still show the old image for a while). Run social-cards:clear --days=90 from your scheduler if you'd like them tidied.
Safety
- Signed URLs. Every card URL carries the card and a signature made with your
APP_KEY. Nobody can ask your app to draw text or fetch images you didn't describe. By default the signature covers the path and query, not the host, so links stay valid behind proxies and load balancers, over http and https, with or withoutwww. RotatingAPP_KEYinvalidates existing card URLs (old keys inAPP_PREVIOUS_KEYSkeep working). - No surprise requests. Local images must sit inside
images.rootsafter symlinks are resolved (../doesn't escape). Remote images are off unless the host is listed, and even then hosts that resolve to private, loopback, link-local or reserved addresses (cloud metadata included) are refused, the connection is pinned to the checked address, redirects aren't followed, and downloads are capped in size and time.file://,phar://,data:and other schemes are refused. - Capped input. Text, image sources and extra data have length limits; images are checked for size and pixel count from their header, before they're decoded.
- No cookies. The image route runs without the
webmiddleware, so responses carry no session cookie and CDNs can cache them.
Your own templates
A template is a class with two methods. It draws on a 1200×630 canvas:
use Ruvelo\SocialCards\Card; use Ruvelo\SocialCards\Contracts\Canvas; use Ruvelo\SocialCards\Contracts\Template; use Ruvelo\SocialCards\Images\Image; use Ruvelo\SocialCards\Theme; class EventCard implements Template { public function version(): string { return '1'; // change it when you change the design: stored cards are drawn again } public function draw(Canvas $canvas, Card $card, Theme $theme, ?Image $image): void { $canvas->gradient(0, 0, 1200, 630, $theme->accent(), $theme->accentAlt(), 'diagonal'); $title = $canvas->text($card->title, 80, 140, 1040, [ 'font' => 'bold', 'size' => 80, 'min_size' => 48, 'max_lines' => 3, 'color' => '#ffffff', ]); $canvas->rectangle(80, 140 + $title->height() + 32, 360, 64, '#ffffff', 32); $canvas->text((string) $card->get('date'), 80, 140 + $title->height() + 44, 360, [ 'font' => 'bold', 'size' => 30, 'color' => $theme->accent(), 'align' => 'center', ]); } }
Register it in a service provider, or in social-cards.templates:
SocialCards::template('event', EventCard::class);
<x-social-cards::meta :title="$event->name" template="event" :data="['date' => $event->starts_at->format('j F')]" />
Try it with php artisan social-cards:preview "Laracon in the park" --template=event. To change a built-in template, register your own under its name (simple, image or split); extending Ruvelo\SocialCards\Templates\BaseTemplate gives you the brand row and the title-and-description fitting the built-in ones use.
The canvas:
| Method | |
|---|---|
fill($color) |
Paint everything |
rectangle($x, $y, $w, $h, $color, $radius = 0) |
Rounded when $radius > 0 |
gradient($x, $y, $w, $h, $from, $to, $direction = 'vertical', $radius = 0) |
horizontal, vertical or diagonal |
image($image, $x, $y, $w, $h, $fit = 'cover', $radius = 0) |
cover crops to fill; contain fits inside |
text($text, $x, $y, $width, $style) |
Wraps and fits, draws, returns the block (->height()) |
layout($text, $width, $style) / draw($block, $x, $y) |
Measure first, then place: e.g. anchor text to the bottom |
measure($text, $size, $font = 'regular') |
One line's width in pixels |
Text styles: font (regular, bold or a font file), size, min_size (shrink down to this to fit), max_lines, max_height, line_height (default 1.25), color, align (left, center, right). Colours are hex strings (#rrggbb, or #rrggbbaa for transparency) or Color objects. The Theme gives you background(), text(), muted(), accent(), accentAlt(), overlay(), logo(), siteName, domain and initial().
For developers
PHP API
use Ruvelo\SocialCards\Card; use Ruvelo\SocialCards\SocialCards; $card = Card::make('Title', 'Description', image: 'images/cover.jpg', template: 'split', data: [...], theme: [...]); $card->withTitle('…')->withImage('…')->withTemplate('image')->withData([...])->withTheme([...]); SocialCards::url($card); // the signed image URL, for og:image SocialCards::generate($card); // draw and store now, unless stored; returns the path on the disk SocialCards::render($card); // the PNG bytes, nothing stored SocialCards::key($card); // the content hash it's stored under SocialCards::path($card); // social-cards/ab/ab12….png SocialCards::forget($card); // delete its stored image SocialCards::clear(days: 90); // delete stored cards; returns how many SocialCards::template('event', EventCard::class); SocialCards::templates(); // name => class SocialCards::image('images/x.png'); // load an image the safe way, for your templates
Routes
GET /social-cards/{key}.png?card=…&signature=… |
The card image. 403 without a valid signature; 404 if the card is no longer valid (its template was removed) |
Commands
social-cards:preview "Title" [--description=] [--image=] [--template=] [--output=social-card.png] |
Draw a card to a file, to try designs without a browser |
social-cards:clear [--days=] |
Delete stored cards |
Events
| Event | When |
|---|---|
SocialCardGenerated |
A card was drawn and stored; has card, disk and path |
SocialCardsCleared |
Stored cards were deleted; has count |
Both in Ruvelo\SocialCards\Events.
Exceptions
All extend Ruvelo\SocialCards\Exceptions\SocialCardsException: InvalidCard (no title, a bad colour, template name or data), UnknownTemplate, ImageNotAllowed (a source the config doesn't allow), InvalidImage (missing, too big, not an image) and RenderingFailed (a driver problem, or an error in a template).
In your tests
Storage::fake('public'); $this->get(SocialCards::url(Card::make('Hello'))) ->assertOk() ->assertHeader('Content-Type', 'image/png'); Storage::disk('public')->assertExists(SocialCards::path(Card::make('Hello')));
Using an AI coding agent?
The package ships Laravel Boost guidelines in resources/boost/guidelines/core.blade.php. With Boost installed (composer require laravel/boost --dev), run php artisan boost:install and pick ruvelo/laravel-social-cards from the third-party packages (or php artisan boost:update --discover if Boost is already set up). Your agent then knows where the tag goes, how to describe a model's card, how to write a template, and not to reach for a headless browser.
Requirements
| Laravel | PHP | Tested in CI |
|---|---|---|
| 12 (12.4.1+) | 8.3, 8.4, 8.5 | yes |
| 13 | 8.3, 8.4, 8.5 | yes |
- PHP's GD extension with FreeType (standard in most PHP builds and Docker images), or Imagick
- A writable disk for the stored cards (
publicby default)
Configuration reference
php artisan vendor:publish --tag=social-cards-config
| Key | Default | |
|---|---|---|
template |
simple (SOCIAL_CARDS_TEMPLATE) |
The template for cards that don't name one |
templates |
[] |
Your templates: name ⇒ class |
theme.background, .text, .muted |
#ffffff, #16162a, #4b4b63 |
Hex colours |
theme.accent, .accent_alt |
#3d4eff, #a78bfa |
The stripe, mark, domain and gradients |
theme.overlay |
#11111cd9 |
Darkens photos in the image template |
logo |
null |
PNG, JPEG, GIF or WebP: under public/, absolute, or an allowed URL |
site_name |
APP_NAME |
On the cards and in og:site_name |
domain |
app.url's host |
Shown on the cards |
fonts.regular, fonts.bold |
bundled Inter | .ttf or .otf paths |
fonts.fallbacks |
[] |
Font files for characters the main fonts lack |
twitter.site |
null (SOCIAL_CARDS_TWITTER) |
Your @handle, for twitter:site |
driver |
gd (SOCIAL_CARDS_DRIVER) |
gd or imagick |
disk |
public (SOCIAL_CARDS_DISK) |
Where cards are stored |
directory |
social-cards |
Folder on the disk |
serve |
file (SOCIAL_CARDS_SERVE) |
file sends the PNG from PHP; redirect sends a redirect to the disk's URL |
cache_seconds |
604800 |
Cache-Control max-age when serving the file |
route.enabled |
true |
Set to false to register the route yourself (copy routes/web.php) |
route.path |
social-cards (SOCIAL_CARDS_PATH) |
URL prefix for card images |
route.domain, route.middleware |
null, [] |
|
signed_urls.absolute |
false |
true to sign the host and scheme too |
images.roots |
public/, storage/app/public |
Folders local images may come from |
images.remote.enabled |
false (SOCIAL_CARDS_REMOTE_IMAGES) |
Fetch images from listed hosts |
images.remote.hosts |
[] |
Exact hosts, or *.example.com |
images.remote.timeout |
5 |
Seconds |
images.max_bytes, images.max_pixels |
5 MB, 25 000 000 | Larger images are refused |
limits.title, .description |
200, 300 |
Characters; longer text is cut at a word |
limits.image, .data |
2048, 20 |
Image source length; number of data values |
pregenerate.enabled |
true (SOCIAL_CARDS_PREGENERATE) |
Draw cards when GeneratesSocialCard models are saved |
pregenerate.connection, .queue |
null |
Where the job goes; null uses your defaults |
Upgrading
First release: nothing to upgrade yet. Future upgrade notes go here.
Contributing
Pull requests are welcome. Clone, composer install, then composer check runs code style (Pint), static analysis (PHPStan level 8) and the tests, exactly as CI does. See CONTRIBUTING.md and the changelog.
Credits
Built by François Bultez at Valtry, the website security scanner, and everyone who contributes.
Inter, the bundled font, is by Rasmus Andersson and the Inter project authors, under the SIL Open Font License 1.1.
License
MIT. See LICENSE. The bundled Inter font files are under the SIL Open Font License 1.1.





