I'm having ongoing problems with laravel 4.1 sessions and getting unexpected behaviour.
Depending on how I call the controllers method the session either works or doesn't My app makes a call to a POST route - to add items to a cart which is a session. For some reason the session does not get updated.However if I make a call to the same function with a GET request the function works as expected.
My routes.php
contains these two routes:
Route::get('testAdd', array('uses' => 'ProductsController@addToCart'));
Route::post('products/addToCart', array('uses' => 'ProductsController@addToCart'));
Both point to the same method
The method is currently this (for testing):
public function addToCart() {
Session::put("addcarttest", "add to cart");
return json_encode(Session::get('addcarttest'));
}
If I call the function with the POST method (with form data) I get the expected result and the contents of the session.
However If I then check for the session (using a profiler) it does not exist. The data did not persist.
If I then call the same method using the GET route, I get the expected result but importantly the session persists.
I thought maybe the POST method deleted sessions however once it exists it stays there - if I use the GET method and the sessin exists if I then try the POST method example again the session remains in place - so the POST method doesnt delete the session.
This is driving me crazy - I've lost a lot of hours over this and can't see why.
Am I missing something over how Laravel handles POST v GET ? Why would two different methods make a difference to underlying functions?
What do I need to do to make the session work correctly with POST?
Update:
I've now tried database driver for the session and am getting the same behaviour.
I've taken my test a stage further- I created a basic form and submitted to the url and the method worked as expected. My current form data is submitted by jquery ajax and assumed they were fairly identical in behviour.
My jquery submit function is this:
$.ajax({
url: '/products/addToCart',
type: 'POST',
async: false,
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
return false;
I set async to false - I assume to await the server response. (doesnt work if true either).
So the problem is a subtle difference between a form submit and an ajax submit. Both methods are hitting the same route and method - one saves the session data - the other one doesnt.
How can I overcome? Jquery submit is essential to this part of the app.
See Question&Answers more detail:
os