Home » Php » php – Laravel – How to use/access session variables in a view?

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

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']))

Answer:

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') }}

Answer:

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