Dynamic meta tags for SEO in Laravel

In this tutorial, I will show you, how you can set dynamic meta tags in your Laravel website for SEO (Search Engine Optimization).

First, you need to set meta tags in your parent layout. Set the value of “content” attribute to the “yield” function. yield is a function in Laravel that receives the value from child layout and render it in parent layout. 1st argument is the key that will be used by child layout, in this case I am using following keys:

  • meta_keywords
  • meta_description
  • title

2nd argument is the default value if no value is provided by child.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    
        <meta name="keywords" content="@yield('meta_keywords', '')" />
        <meta name="description" content="@yield('meta_description', '')" />
        <title>@yield("title", "")</title>

    </head>

    <body>
        <p>Header</p>

        @yield("main")
    
        <p>Footer</p>
    </body>
</html>

Now we need to pass those values from child layout. In child, we will use the “section” function and it’s 1st argument will be the key set in @yield in parent child. 2nd argument will be the value that you need to set for that page.

@extends ("layouts/app")

@section ("meta_keywords", "my,keywords,goes,here")
@section ("meta_description", "this is my page description")
@section ("title", "this is my title")

@section ("main")
    <p>Main</p>
@endsection

If you refresh the page now, you will see your provided meta keywords, description and title. That’s how you can set dynamic meta tags in your Laravel website for better SEO.

I started as a PHP developer. Then I switched to become Node.js developer for almost 3 years. Now I switched it back to PHP. There is a reason why I switched from Node.js back to PHP, check it out.