Perfect Web Group

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

By Abdullah Saad 19 Views 4 min read
Code editor showing a Laravel Blade JSON-LD component and a toSchema model method

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

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,
    ];
}

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

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

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(),
    ];
}

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],
]" />

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']);

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.

Frequently Asked Questions

Is there a package for JSON-LD in Laravel?

Yes, several packages exist. A small custom component like this one avoids extra dependencies and keeps full control over the output.

Where should the JSON-LD component go?

Usually in the main layout's head, with each page passing its schema data through a section or stack.

How do I validate the output?

Use Google's Rich Results Test and the Schema Markup Validator, plus automated feature tests in your Laravel test suite.

Published by Abdullah Saad

Comments

Comments appear after admin approval.

0
No comments yet. Be the first to share your thoughts.