0

I'm using AJAX post request to set session values with Laravel 5.4 :

$.post('http://www.example.com/api/setSessionValue', {
  "data": data
})
public function setSessionValue() {
    $data = Input::get('data');
    // ...
    Session::put('value', $data);
}

But my value is never set in session, or set but non persistent.

I can't understand why since I'm already using session in the same way in my Laravel project, and it's working fine.

EDIT:

I forgot to specify that in in development mode (artisan serve), it's working absolutely fine.

zronn
  • 1,026
  • 8
  • 26
  • Have you debugged this at all, to determine if the value is what you expect it to be in JS, and is sent correctly, and received properly on the server? – Rory McCrossan Jan 12 '18 at 09:34
  • Yes I did, the post request is working fine. Also `$data` is a PHP array correctly valued by the data I want to receive. – zronn Jan 12 '18 at 09:37
  • try using `Request` like `$request->data` – JoshKisb Jan 12 '18 at 09:38
  • @JoshKisb I did it, still not working. – zronn Jan 12 '18 at 09:46
  • Does the fact that you are using an absolute URL here mean that this is a cross-domain request? In that case, please go read up on what you need to do to get cookies send with it. – CBroe Jan 12 '18 at 09:59
  • @CBroe Yes it is. By reading your post I found some informations about configurations to set in `config/session.php`, but nothing concrete. Do you have other information to tell me about what you said ? – zronn Jan 12 '18 at 10:20
  • https://stackoverflow.com/questions/3342140/cross-domain-cookies – CBroe Jan 12 '18 at 10:32

1 Answers1

2

From the looks of it, you most likely are storing your API routes in the the routes/api.php file. That file uses a separate group of middleware that does not maintain state (does not use the StartSession middleware), as APIs by design, should be stateless.

If you must, try moving your API routes in to the routes/web.php file to see if it works. If it does, you can add the following middleware to the API middleware group in app/http/kernel.php

 \Illuminate\Session\Middleware\StartSession::class,
Rob Fonseca
  • 3,671
  • 2
  • 17
  • 13