TALL Tales

Home About Resources Reference Posts Contact

How to Add a Dynamic Title and Description to the Head

26 Feb, 2021

TUTORIAL

LARAVEL

Depending on what kind of website you are building you will probably want to have a different <title> and <meta name="description"> for each page you are displaying. Using Laravel you will need to feed these in dynamically because it is most likely that will have a layout file that has the <html>, <head> and <body> sections of your site.

So, for example, on this site I have my main layout (main.blade.php) in 'resources/views/layouts/'. In this file I have added the following code:

<title>TALL Tales: {{$title}}</title>
<meta name="description" content="{{$extract}}" />

Then on each page that I use this particular layout I call it by putting my code in:

<x-main-layout>
//specific page stuff here
</x-main-layout>

To pass in the required data for $title and $extract I add this to the opening tag:

<x-main-layout title="{{ $post->title }}" extract="{{ $post->extract}}">
//specific page stuff here
</x-main-layout>

This takes the data for the particular Post you are reading and then feeds it to the layout php file and if you do view source on this page you will see it will have added it in.

Photo by Sai Kiran Anagani on Unsplash

Did this article help you? Say thanks by buying me a coffee!