Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

JeffBeltran's avatar

Unable to access session data in my "layout" file but no problem from the yielded section

So this will be a super trimmed down version but in short i have my layout file with something like

<div class="page-content" id="app">
    <p>{{ session('flash_notification') }}</p>
                
   @yield('content')
 </div>

the content block is pretty much this

@extends('layouts.app')

@section('content')
    <p>{{ session('flash_notification') }}</p>
@endsection

The controller function looks like this

public function index()
{
    Flash::message('Test Message', 'success');

    return view('model.index')
}

So my question is why is the session data not shown twice? Once from the layout file and once from the content block?

For me, the layout file portion is returning empty but in the “content” block it shows the expected flash message.

Not sure if i'm missing something but any help in pointing me in the right direction would be appreciated

Thanks

0 likes
2 replies
JeffBeltran's avatar

Ok so i got it working the way i want by using View Composers

class AppServiceProvider extends ServiceProvider
{
    view()->composer('layouts.app', function ($view) {
            if (\Session::has('flash_notification')) {
                $view->with('flash_notification', \Session::get('flash_notification'));
            }
        });

Now all my views will have {{$flash_notification}} available if it is defined

So I guess my question would be… Is this the best way? Or am I adding a bunch of overhead I don’t need?

Snapey's avatar

out of the box, a session variable of 'status' is echoed with

                    @if (session('status'))
                        <div class="alert alert-success">
                            {{ session('status') }}
                        </div>
                    @endif

I'm not sure why you are expecting the session variable to be called 'flash_notification' ?

Please or to participate in this conversation.