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 isen-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.
| Field | Purpose | Example value |
|---|---|---|
| locale | Language code of the version | tr, en, de |
| slug | URL segment of the version | pump-selection-guide |
| translation_group_id | Groups the versions of the same content | a single UUID |
| published | Only published versions enter the annotation set | true / 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:
- Confirm in the rendered HTML that each language has exactly one
hreflangtag. - Check that every URL in the list returns a 200 response and is indexable; redirects and noindex targets are not acceptable.
- Verify that every target page carries the return tag, which proves that the annotations are reciprocal.
- Review that language codes follow ISO standards, especially the capitalization and hyphen usage in region codes.
- Test that when a page is unpublished, both the list and the cache reflect the change.
- 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.
| Error | Symptom | Fix |
|---|---|---|
| Missing return tag | The counterpart page does not confirm the link | Calculate the list separately for each version |
| Invalid region code | Codes such as en-UK do not work | Use ISO 3166-1 Alpha-2 (en-GB) |
| Relative URL | The annotation resolves against the wrong host | Always output full URLs |
| Draft version in the list | A page that is not live gets shown | Add a published filter to the query |
| Cache mix-up | The wrong language's list is served | Include language and page ID in the cache key |
| Redirect chains | The target cannot be reached directly | List 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.




No comments yet
Leave a Comment