Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

singh's avatar
Level 1

Laravel 8.0 Canonical URL meta tag

How do I generate a canonical URL for every page on my Laravel app? Basically, I am building a content management system that will have thousands of pages each requiring a canonical link pointing to www.sitename.com/path-to-page

0 likes
7 replies
MichalOravec's avatar
@if (Str::startsWith($current = url()->current(), 'https://www'))
    <link rel="canonical" href="{{ str_replace('https://www.', 'https://', $current) }}">
@else
    <link rel="canonical" href="{{ str_replace('https://', 'https://www.', $current) }}">
@endif

or you can create a helper for that

if (! function_exists('canonical_url')) {
    function canonical_url()
    {
        if (\Illuminate\Support\Str::startsWith($current = url()->current(), 'https://www')) {
            return str_replace('https://www.', 'https://', $current);
        }

        return str_replace('https://', 'https://www.', $current)
    }
}
<link rel="canonical" href="{{ canonical_url() }}">
2 likes
singh's avatar
Level 1

This is almost there. A minor correction - www needs to be www. else url becomes wwwmysite.com instead of www.mysite.com. Otherwise the code works. I didn't need to create a helper function.

1 like
MichalOravec's avatar

@singh Yeah you are right, I usually don't test a code.

So mark this thread as solved. Thanks.

1 like
cocotmu's avatar

@MichalOravec what about URL with parameter? example

domain/agent?page=1 canonicalize as domain/agent

domain/agent?page=2 also canonicalize as domain/agent

sorcjc's avatar
sorcjc
Best Answer
Level 1

@cocotmu In that case you can use something like this:

@if ($articles->currentPage() === 1)
<link rel="canonical" href="{{ url()->current() }}" />
@else
<link rel="canonical" href="{{ url()->current() }}?page={{ $articles->currentPage() }}" />
@endif

Please or to participate in this conversation.