sajad torkamani

It's good practice to set descriptive <title> attributes for each web page. There are SEO and user experience benefits. For example, the <title> is usually used in a search engine's results page and it's also used as the default name for a browser bookmark.

Laravel's Blade templating system makes it easy to do this. There are essentially two steps.

1. Yield the title in your layout file

Create a layout component with something like the following content:

<!-- resources/views/components/layout.blade.php -->

<html>
  <head>
    <title>
      @hasSection('title')
        @yield('title') | {{ config('app.name') }}
      @else
        {{ config('app.name') }}
      @endif
    </title>
    </head>
    <body>
        {{ $slot }}
    </body>
</html>

2. Set the title from each view

Now, you can use the @section directive to set the title value like so:

<!-- resources/views/auth/register.blade.php -->

@section('title', 'Register')

<x-main-layout>
  <!-- page contents... -->
</x-main-layout>
<!-- resources/views/auth/login.blade.php -->

@section('title', 'Login')

<x-main-layout>
  <!-- page contents... -->
</x-main-layout>

That's a pretty simple approach that gets the job done. You could also pass the page title as a component prop but this approach is good enough in most cases.

Tagged: Laravel