Set Dynamic Title & Description in Laravel Blade App

In this article, I’m going to show how to set dynamic title and meta description in the Laravel with blade view application. Let’s get started:

Table of Contents

  1. Modify App Layout
  2. Pass Data to Blade from Controller

Modify App Layout

Open your application layout view file from resources/views folder. Then replace title, description tags with this:

<title>{{ isset($title) ? $title . ' - ' . config('app.name', 'Laravel') : config('app.name', 'Laravel') }}</title>
<meta name="description" content="{{ isset($description) ? $description : 'Default description.' }}">

So, the app layout looks like:

app.blade.php
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<!-- CSRF Token -->
	<meta name="csrf-token" content="{{ csrf_token() }}">

	<!-- Dynamic title and description -->
	<title>{{ isset($title) ? $title . ' - ' . config('app.name', 'Laravel') : config('app.name', 'Laravel') }}</title>
	<meta name="description" content="{{ isset($description) ? $description : 'Default description.' }}">

	<!-- Scripts -->
	<script src="{{ asset('js/app.js') }}" defer></script>

	<!-- Fonts -->
	<link rel="dns-prefetch" href="//fonts.gstatic.com">
	<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">

	<!-- Styles -->
	<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
	<main>
			@yield('content')
	</main>
</body>
</html>

Pass Meta Data from Controller

Now we’ll use title, description from controller. Have a look at the example:

PageController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PageController extends Controller
{
  /**
   * home.
   */
  public function home()
  {
    $title = "Home";
    $description = "This is home page";

    return view('home', compact('title', 'description'));
  }

  /**
   * about.
   */
  public function about()
  {
    $title = "About";
    $description = "This is about page";

    return view('about', compact('title', 'description'));
  }
}

Have a look at the home.blade.php file:

home.blade.php
@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ $title }}</div>
            </div>
        </div>
    </div>
</div>
@endsection

Done. Now you can visit home, about page and have a look at the title. You can also inspect to see the title and description.

That’s all. Thanks for reading.