How to access declared variable from laravel-livewire component in the app layout

Viewed 4129

I tried passing a variable from livewire component:

class Index extends Component
{
    public function render()
    {
        return view('livewire.index')->with('type', config('constants.NONAUTH'));
    }
}

and accessing it from layouts.app:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

{{dd($type)}}

@include('includes.head')

...

I get an error that $type is not defined, what is the correct way of doing this?

1 Answers

declare a public variable $type and set this variable inside your mount() function like this:

class Index extends Component
{
    public $type = null;
    
    public function render()
    {
        return view('livewire.index');
    }

    public function mount() 
    {
         $this->type = config('constants.NONAUTH');
    }

}

Edited:

I see, I got you wrong first time,. I read again and came to understand that the thing you want , wont work becuase you are trying to access a variable which is declaring after your app layout. Livewire render its component right after your layout loads. I would recommend you to make your whole app layout using livewire.

Yes there could be various way of declaring something from livewire into your blade. Here is one:

You can fire an event which can be listened by global JS inside your blade. then you can set that value inside your blade component using jquery / vanilla js.

Related