Malith Senanayake
Malith Senanayake

Reputation: 466

How to pass page title to views through controller in Laravel 8?

I'm trying to dynamically pass each page title to views via the controller. I have included the page header inside the views/components folder and passing it to each view as <x-header></x-header>. Then in the header tag I'm trying to echo the page title as {{$title}}, but I get the error "Undefined variable $title". How to debug this error?

Controller

public function index() {
    $title = "Home || My site";
    return view('home', compact('title'));
}

header.blade.php file in components/header

<head>     
    <title>
        {{ $title }}
    </title>
</head>

home.blade.php view with header included on top

<x-header></x-header>
<div class="search-relative search-relatives " id="search-relatives">
<div class="item height25vh" id="vid">

Upvotes: 2

Views: 1850

Answers (2)

Rashed Rahat
Rashed Rahat

Reputation: 2475

Try:

<x-header>{{ $title ?: 'Default Value' }}</x-header>

Upvotes: 1

Localhousee
Localhousee

Reputation: 912

Set your components attribute correctly

<x-header :title=$title></x-header>

I assume you already setup your header.php file

Docs

Upvotes: 2

Related Questions