Reputation: 115
Was wondering if it is possible. My attempt is to have a dark mode checker within the PHP controller and send it back to the body as an if statement checking if the boolean is true or not.
Here's my current work:
Sender URL
<a href="/nightmode"> Switch modes</a>
Controller
public function switchModes()
{
//doesnt work since $isDark's value is not initialized
$isDark = !$isDark;
dd($isDark);
return $isDark;
}
Target result:
<body background="@if($isDark) #505050 @else #ffffff @endif">
Upvotes: 0
Views: 4569
Reputation: 337
The short answer is yes. But you should really try to make your question clearer.
If you want user to click a button or link to switch between light/dark modes, you should use Session
.
In your current controller method, you commented that $isDark
isn't initialized. You didn't provide a way to initialize that value anywhere, and your controller has no way to figure out what you are doing.
By using session variables, you can have values that persist between pages.
Learn more about sessions
here: PHP Session Introduction
Session
in Laravel
works a little different, but the idea is the same. You want to fetch a session variable in your controller method, and check the value to determine if the user is under light or dark mode, then you would switch his mode by setting the session variable to the other value. In your view, you can check related session variable to determine the mode.
In your controller, you may want to do something like:
public function switchModes()
{
if (session()->has('isDark')) {
session()->put('isDark', !session('isDark'));
}
else {
//provide an initial value of isDark
session()->put('isDark', true);
}
return redirect()->route('your-route-name');
}
And in your view, you can check the session variable like this:
<body class="@if (session('isDark')) dark-mode @else light-mode">
Upvotes: 3