user9459623
user9459623

Reputation:

Laravel can't set session variable

The script never hits the route to set the session variable.

Script that sends the data that needs to be put into a session variable.

<script>
         $(document).ready(function() {             
                var timezone = "PST";

                $.ajax({
                    type: "POST",
                    url: "/set_session",
                    data: { "timezone": timezone },
                    success: function(){
                        location.reload();
                    }
                });
            })
    </script>

- Here is my route that will be used to set the session variable.

Route::post('/set_session', 'SetSessionsController@create');

- This is my controller that sets the session.

class SetSessionsController extends Controller
{

    public function create(Request $request)
    {
        session(['timezone' => $request->get('timezone');
    }

}

Upvotes: 1

Views: 1543

Answers (1)

Sletheren
Sletheren

Reputation: 2478

You have a typo there:

session(['key' => 'value']);

So your code should be:

session(['timezone' => $request['timezone']]);

You can Access it in the blade template using:

@if(Session::has('timezone')))  
  {{ Session::get('timezone')}}
@endif

Upvotes: 2

Related Questions