简体   繁体   中英

Laravel - How to use/access session variables in a view?

I only find information on how to save a session variable which works like this: $request->session()->put('key', 'value');

But how can I access the session in a blade view?

Just use session() helper to read the data:

{{ session('key') }}

Or:

{{ request()->session()->get('key') }}

If you want to store something, do this:

@php(session(['key' => 'value']))

Its quite simple as core php, you can use its facade in blade or a method like,

{{Session::get('key')}}

Or by method like,

{{ session()->get('key') }}

In case you have a session variable called $mySessionVar and inside you have key value pair information then you could use:

<p>
    @if(Session::has('$mySessionVar'))
        {{ Session::get('mySessionVar')['keyName'] }}
    @endif
</p>

And in case the value is an array (key/value pair) you could use:

@foreach(Session::get('mySessionVar')['keyName'] as $variableName)
    <span>{{ $variableName }} </span>
@endforeach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM