Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tuyenlaptrinh's avatar

Laravel 9 Session does not work

Hello. I am set session via AJAX call. with below code

Controller

...
public function set_dark_theme(Request $request)
    {
        if(Session::has('dark_theme')) {
            Session::remove('dark_theme');
        }
        else{
            $visit_time = date('F j, Y  g:i a');
            Session::put('dark_theme', $visit_time);
        }
        die();
    }
....

view

@php
$bodyClass = '';
if(session()->has('dark_theme')){
    $bodyClass .= ' dark';
}
@endphp

After AJAX call done. I press refresh page (F5). The session is NULL.

0 likes
12 replies
AungHtetPaing__'s avatar

@tuyenlaptrinh I think you don't need to make Ajax call and set session. Use localStorage to set theme.

Code from tailwind doc

// On page load or when changing themes, best to add inline in `head` to avoid FOUC
if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
  document.documentElement.classList.add('dark')
} else {
  document.documentElement.classList.remove('dark')
}

// Whenever the user explicitly chooses light mode
localStorage.theme = 'light'

// Whenever the user explicitly chooses dark mode
localStorage.theme = 'dark'

// Whenever the user explicitly chooses to respect the OS preference
localStorage.removeItem('theme')

https://tailwindcss.com/docs/dark-mode

1 like
tuyenlaptrinh's avatar

@AungHtetPaing__ Yes. I used that before. But We will see jump flash with white background before render dark background. I added javascript after body tag.

Sinnbeck's avatar

Is this route in api.php? Session is disabled for api routes

tuyenlaptrinh's avatar

@Sinnbeck I put route in web.php. I can get session after set in ajax request but lose after reload page

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@tuyenlaptrinh ah I just noticed you have die();. This stops the session being sent to the browser. Remove that and let laravel handle the response

1 like

Please or to participate in this conversation.