Skip to content
Advertisement

How to echo session variable in laravel?

I have created a session variable and it’s value in laravel blade using plane javascript. But when I am trying to get that session variable value in my blade page, it displays nothing . My codes are :

@extends('ui.layout.app')

@section('content')
 <div class="get-session">

    <select id="setSession" onchange="myFunction()">
      <option value="5">5</option>
      <option value="10">10</option>
    </select>
    <p id="get_session"></p>
    here : {{ Session::get('currency_code')}}
 </div>

 <script type="text/javascript">
    function myFunction() {
      var x = document.getElementById("setSession").value;
      sessionStorage.setItem("currency_code", x);
      document.getElementById("get_session").innerHTML = "You selected: " + x;
    }
  </script>  
@endsection

Advertisement

Answer

I guess you are putting the session variables to the normal php (cookie based) session. But you want to recieve them by using the laravel-session facade. That is not the same!

You can configure laravel to use different “session driver” as “file”, “cookie” or even queue-services like “redis”.

Thats why your Session->get(…) wont revieve the values you set without laravel.

To solve that create a route for saving data to session, pass it by javascript post call to that route. Use laravel Storage facade to put that request payload into the session. Than display it in your views.

See also https://laravel.com/docs/8.x/session

Advertisement