DELTAWEB
All posts
Web Development

Generating hreflang Dynamically in Laravel: A Code Guide

Generate hreflang tags dynamically in Laravel per language: service class, Blade template, validation steps and common errors, with short code examples.

Generating hreflang Dynamically in Laravel: A Code Guide
9 minReading time
Arif KuruAuthor

Let's start with a hypothetical case: an industrial pump manufacturer has its product page live in Turkish, English and German, yet a buyer in Germany still sees the English version in search results and the German page never appears. The root cause is rarely translation quality. It is almost always a missing or inconsistent language connection between the pages. This guide assumes you already know the basics of hreflang and shows how to generate these tags dynamically from the language versions stored in a Laravel application's database.

Key Takeaways

  • Every hreflang set must list all language versions, including the page itself, and every link must be reciprocal.
  • In Laravel, build the list in one service class from a translation group, not by hand in Blade.
  • Every URL in the list must be absolute, return a 200 response and be indexable.
  • The view should only loop; the logic stays in the service.
  • Check the output together with your cache and your sitemap.

Start with Google's rules

Dynamic generation only works if you respect the mandatory rules first. Google's official hreflang documentation describes three ways to supply the annotations: the HTML link element, HTTP headers and the XML sitemap. This article focuses on the most common method, the HTML element; the sitemap approach is covered later in the article.

Three core rules apply to every method:

  • Language and region codes: The language uses an ISO 639-1 code (tr, en, de), and an optional ISO 3166-1 Alpha-2 region code can follow it (en-GB, de-DE). A value such as "en-UK" is invalid; the correct code for the United Kingdom is en-GB.
  • Reciprocity: If page A points to page B, page B must point back to page A. One-way annotations are not considered reliable and may be ignored.
  • Absolute URLs and self-reference: Every annotation must use a full URL, and the page must list itself.

When should x-default be used?

x-default names the fallback page shown when the user's language does not match any version. A language selector page or the main-language version usually fills this role. It is not mandatory for every group, but once you add it, the target page must really be live. For details, see the x-default setup guide.

Data model: the translation group concept

The foundation of dynamic generation is a key that connects the language versions of the same content. That key can live in a separate table, or it can be a translation_group_id column stored on every row. What matters is that you can reach every other version of a page from any one version with a single query.

FieldPurposeExample value
localeLanguage code of the versiontr, en, de
slugURL segment of the versionpump-selection-guide
translation_group_idGroups the versions of the same contenta single UUID
publishedOnly published versions enter the annotation settrue / false

In this model, the hreflang list for a page is the list of published records in the same group. Generating an annotation for an unpublished version means pointing search engines to a page that cannot be reached. That is why adding a publication filter to the query is the simplest and most valuable safeguard.

Service layer: the class that builds the hreflang list

Keeping the annotation logic in a service class instead of writing it into the Blade template improves both testability and consistency. The example below starts from a generic Page model; adapt it to the model and URL structure of your own project.

namespace App\Services;

use App\Models\Page;

class HreflangService
{
    /** Language code in the app => hreflang value */
    private array $codes = [
        'tr' => 'tr',
        'en' => 'en',
        'de' => 'de',
    ];

    public function for(Page $page): array
    {
        $siblings = Page::query()
            ->where('translation_group_id', $page->translation_group_id)
            ->where('published', true)
            ->get();

        $links = [];

        foreach ($siblings as $sibling) {
            if (isset($this->codes[$sibling->locale])) {
                $links[$this->codes[$sibling->locale]] = $sibling->absoluteUrl();
            }
        }

        if (isset($links['tr'])) {
            $links['x-default'] = $links['tr'];
        }

        return $links;
    }
}

Three points deserve attention in this class. First, the query returns only published records, so draft versions never enter the annotations. Second, the current page is part of the list, so self-reference is provided automatically; if the page itself is unpublished, the list can come back empty and the caller must handle that case. Third, absoluteUrl() is a helper on your model that produces a full address and should never output a relative one.

Output in a Blade template

Once the service has built the list, the view layer only needs to loop over it. In the controller, the array returned by app(HreflangService::class)->for($page) is passed to the view, and the tags are rendered in the page's head section, next to the canonical tag.

@foreach ($alternates as $lang => $href)
    <link rel="alternate" hreflang="{{ $lang }}" href="{{ $href }}">
@endforeach

Avoid adding extra conditions in the template. If the list is empty, no tags should be printed. A list with a single entry is also meaningless, because it only contains the self-reference. In that case, printing no tags at all is usually the better choice.

Pages without equivalents

Not every page needs an equivalent in every language. In the hypothetical example, a certification page that has no German version does not get a German annotation; the list only contains the versions that exist. The core rule is this: every version in the list must show the same group in its own list. If the Turkish page points to the English version, the English page must point back to the Turkish one. A page without an equivalent produces no tags and simply stays live in its own language.

This distinction matters most for exporters with large product catalogs. Not every product needs to be translated into every language, but untranslated pages must never be linked to the wrong language through annotations.

Middleware and shared view data

If several templates need the same annotation list, a View Composer is a cleaner option than recalculating the list in every controller. If you use middleware to route users by language, the important point is that the hreflang output must be based on the real language version of the page, not on the user's preference. Search engine crawlers do not carry a browser language, so this distinction is critical: output that changes with the browser language changes the tags that the crawler sees.

Also, in systems that use full-page caching, make sure the cache key includes the language and the page identifier. Otherwise, one language's page can be served with another language's hreflang list. This error is silent and only shows up once the cache entry expires, so clearing the cache and checking again during testing is a good habit.

Headless and Next.js setups

In architectures where Laravel runs only as an API and the front end is served by a separate framework, annotation generation can move to the front end or be handed to a separate sitemap service. In such setups it is critical that the generation logic does not produce different results on the two sides; otherwise the same page ends up with two conflicting lists. For the Next.js approach, see the article on hreflang in Next.js and headless sites.

Alternative methods: HTTP headers and sitemaps

HTML annotations live inside the page, but for non-HTML files such as PDFs the annotation is delivered through an HTTP header. On large sites, collecting all annotations in an XML sitemap reduces page size and makes management easier. Whichever method you choose, the three methods must not contradict each other for the same language group. For the details of the sitemap approach, read the guide on implementing hreflang via XML sitemaps.

Validation steps

Writing the code is only half the job. Running these checks before and after publishing is the most practical way to catch silent errors:

  1. Confirm in the rendered HTML that each language has exactly one hreflang tag.
  2. Check that every URL in the list returns a 200 response and is indexable; redirects and noindex targets are not acceptable.
  3. Verify that every target page carries the return tag, which proves that the annotations are reciprocal.
  4. Review that language codes follow ISO standards, especially the capitalization and hyphen usage in region codes.
  5. Test that when a page is unpublished, both the list and the cache reflect the change.
  6. Monitor the international targeting and page reports in Google Search Console on a regular basis.

Running these checks by hand across an entire site is tedious. An audit tool that crawls every URL is a reasonable way to automate them. When choosing a tool, look beyond whether a tag exists and confirm that it also checks return tags.

Common errors

The most frequent problems in dynamic generation are caused by data and caching more often than by code. For a broader list of mistakes, see the international SEO guide on hreflang errors.

ErrorSymptomFix
Missing return tagThe counterpart page does not confirm the linkCalculate the list separately for each version
Invalid region codeCodes such as en-UK do not workUse ISO 3166-1 Alpha-2 (en-GB)
Relative URLThe annotation resolves against the wrong hostAlways output full URLs
Draft version in the listA page that is not live gets shownAdd a published filter to the query
Cache mix-upThe wrong language's list is servedInclude language and page ID in the cache key
Redirect chainsThe target cannot be reached directlyList only URLs that return 200 directly

Most of the errors in this table can be prevented with one service class and a regular test set. Running the checklist after every publication stops these problems from piling up.

Conclusion and next step

Moving hreflang generation in Laravel into a service class keeps the translation group logic in one place and ensures the annotations always match the published versions. Keep the code short and simple; most of the complexity is usually solved in the data model. As a next step, audit your current site for reciprocity problems and compare the results with the guide on detecting and fixing return tag errors. Once the connections between your language versions are set up correctly, it becomes far more likely that search engines show the right version to the right user.

FAQ

Frequently Asked Questions

  • Why should hreflang tags be generated dynamically in Laravel?

    Because the language counterparts of each page change in the database: when a new version goes live or a page is removed, the tag list must change as well. Hand-written tags cannot keep up with these changes, and broken connections accumulate. With dynamic generation, the list is calculated from the published records on every request.

  • Which language code should be used for hreflang?

    An ISO 639-1 language code (tr, en, de) is sufficient. When a region is needed, an ISO 3166-1 Alpha-2 code is added, for example en-GB or de-DE. Codes such as en-UK are invalid; the correct code for the United Kingdom is en-GB.

  • Is the x-default annotation always required?

    No, it is not mandatory. It tells search engines which page to show when the user's language matches none of the versions. If you add it, the target page must be published and indexable.

  • How should hreflang be handled when a page has no translation?

    No annotation is generated for a version that does not exist. The existing versions stay reciprocally linked to each other, and the untranslated page stays live only in its own language. Linking an untranslated page to another language's version can send users to a page in the wrong language.

  • Where should hreflang tags be placed?

    In the head section of the HTML page, next to the canonical tag. They are printed with a loop in the view template, and no tags should appear when the list is empty. Non-HTML files can use HTTP headers instead.

  • How does caching affect hreflang output?

    If the cache key does not include the language and the page identifier, one language's page can be served with another language's tags. This error is silent. Tie the cache key to the page and the language, and clear the relevant cache whenever a version is published or unpublished.

  • How can I test hreflang output in Laravel?

    Check the rendered HTML source for exactly one tag per language. Then confirm that every URL in the list returns a 200 response and that each target carries a return tag. For the whole site, a browser-based or crawler-based audit tool can automate this check.

  • Why is reciprocity so important?

    Search engines expect a page that points to another version to be confirmed by that version through a return tag. One-way annotations may be ignored, which leaves unclear which version serves which language. When the service builds the list from the same group for every version, reciprocity is provided automatically.

Related Articles

No comments yet

Leave a Comment