Search code examples
laravellaravel-livewire

Laravel 8 Livewire component Undefined variable: header


I have created a Livewire component in Jetstream and I have set it as a full-page component in the web.php route page as follows:

use App\Http\Livewire\PostComponent;
...
Route::get('posts/',PostComponent::class)->name('posts');

The post-component.blade.php file has originally the following code:

<div>
    <h1>If you look to others for fulfillment, you will never truly be fulfilled.</h1>
</div>

If I hit the URL .../posts I get the following error:

Undefined variable: header (View: /home/vagrant/laravelapp/resources/views/layouts/app.blade.php)

So I have tried adding the slot in the post-component.blade.php file:

<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            {{ __('Dashboard') }}
        </h2>
    </x-slot>
    <div>
        <h1>If you look to others for fulfillment, you will never truly be fulfilled.</h1>
    </div>
</x-app-layout>

Nevertheless, I get that same error.

What am I missing? How do I fix this?


Solution

  • I hope this is a Jetstream project. By default, livewire will use the app.blade.php as the layout. And the component will get rendered in the slot of the app.blade.php.

    But since it's a Jetstream project, it has a slot for the header in the layout file.

      <header class="bg-white shadow">
           <div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
                 {{ $header }}
            </div>
      </header>
    

    So to resolve this error, there are two approaches.

    1. give the header as the variable for the layout as below in your PostComponent.php
    
     public function render()
     {
            return view('livewire.post-component')
             ->layout('layouts.app', ['header' => 'Post Compoent Page']);
     }
    
    1. Create your own layout and only have a slot. (imagine mylayout.blade.php)
    
    <head>
        @livewireStyles
    </head>
    <body>
        {{ $slot }}
    
        @livewireScripts
    </body>
    
    

    and use that layout when rendering the livewire component

    public function render()
    {
       return view('livewire.post-component')->layout('layouts.mylayout');
    }
    

    There is a github issue regarding this topic (a closed one). But keep an eye on it. since Jetstream is in it's early stages.