DEV Community

Cover image for Generating JSON-LD Structured Data in Laravel With a Blade Component
Perfect Web Group
Perfect Web Group

Posted on Originally published at perfectwebgroup.com

Generating JSON-LD Structured Data in Laravel With a Blade Component

Hand-written structured data goes stale as soon as titles, dates or prices change. The fix is to generate it from the same data that renders the page. This tutorial shows a clean way to produce Laravel JSON-LD with a small Blade component and model methods, so every page outputs valid, consistent schema automatically. For copy-ready schema shapes, see our JSON-LD schema templates.

1. Create the Component

Generate an anonymous Blade component at resources/views/components/json-ld.blade.php:

@props(['data'])
@if (! empty($data))
<script type="application/ld+json">{!! json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG) !!}</script>
@endif
Enter fullscreen mode Exit fullscreen mode

The JSON_HEX_TAG flag escapes < and >, so content such as a title containing </script> cannot break out of the script element. JSON_UNESCAPED_UNICODE keeps Arabic text readable.

2. Add a Schema Method to the Model

Keep schema logic close to the data. For a blog post model:

public function toSchema(): array
{
    $url = route('posts.show', $this);

    return [
        '@context' => 'https://schema.org',
        '@type' => 'BlogPosting',
        '@id' => $url.'#article',
        'headline' => $this->title,
        'description' => $this->meta_description,
        'image' => $this->featured_image_url,
        'datePublished' => $this->published_at?->toIso8601String(),
        'dateModified' => $this->updated_at?->toIso8601String(),
        'author' => ['@type' => 'Person', 'name' => $this->author?->name],
        'publisher' => ['@id' => url('/').'#organization'],
        'mainEntityOfPage' => $url,
    ];
}
Enter fullscreen mode Exit fullscreen mode

Remove empty values before output so optional fields never appear as null:

return array_filter($schema, fn ($v) => $v !== null && $v !== '');
Enter fullscreen mode Exit fullscreen mode

3. Build Breadcrumbs From the Route

public static function breadcrumbs(array $items): array
{
    return [
        '@context' => 'https://schema.org',
        '@type' => 'BreadcrumbList',
        'itemListElement' => collect($items)->values()->map(fn ($item, $i) => array_filter([
            '@type' => 'ListItem',
            'position' => $i + 1,
            'name' => $item['name'],
            'item' => $item['url'] ?? null,
        ]))->all(),
    ];
}
Enter fullscreen mode Exit fullscreen mode

Use the same array to render the visible breadcrumb trail, so markup and page always match. Our breadcrumb schema guide explains the rules.

4. Combine Into a Graph

Instead of several unrelated scripts, output one @graph that links your Organization, WebPage and Article through @id references:

<x-json-ld :data="[
    '@context' => 'https://schema.org',
    '@graph' => [$organization, $post->toSchema(), $breadcrumbs],
]" />
Enter fullscreen mode Exit fullscreen mode

Remove the inner @context keys when nesting inside a graph. Connected entities help search engines understand relationships, as discussed in our guide to entity SEO.

5. Cache Where It Helps

Schema generation is cheap, but organisation data that rarely changes can be cached in configuration or a settings cache. Avoid caching per-page schema separately from the page; regenerate it whenever the page is rendered or cached.

6. Test It

A feature test can decode the output and assert key fields:

$html = $this->get('/'.$post->slug)->assertOk()->getContent();
preg_match('~<script type="application/ld\+json">(.*?)</script>~s', $html, $m);
$json = json_decode($m[1], true);
$this->assertSame($post->title, $json['@graph'][1]['headline']);
Enter fullscreen mode Exit fullscreen mode

Also validate a sample of live pages with Google's Rich Results Test after each release.

Common Pitfalls

  • Outputting relative image or page URLs; always use absolute URLs.
  • Marking up content that is not visible on the page.
  • Using {{ }} instead of a raw JSON output, which HTML-escapes quotes and breaks the JSON.
  • Forgetting to update dateModified when content changes meaningfully.

Our web development team builds automated schema, canonicals and sitemaps into Laravel projects as standard. For a wider checklist, see our Laravel technical SEO audit.


Originally published on Perfect Web Group.

Top comments (0)