in my webpage layout i have a modal which whenever user register or some event happens simply i show on the top of screen.i am using Laravel blade template engine and i use session() function to send data to front-end.
My modal:
@if(session()->has('message'))
<div x-data="{show: true}" x-init="setTimeout(() => show = false, 3000)" x-show="show"
class="fixed top-0 left-1/2 transform -translate-x-1/2 bg-laravel text-white px-48 py-3">
<p>
{{session('message')}}
</p>
</div>
@endif
as u can see if there is message in session then shows msg so simple.
Corresponding Controller:
public function index()
{
session()->put('message', 'Test Msg');
$listings = Listing::latest()
->filter(request(['tag', 'search']))
->paginate(4);
return view('listings.index', compact('listings'));
}
as u can see here i have dummy session message.The problem is when i show this dummy msg and remove it shows itself again however i remove it from code even i restart php server.
as my knowledge session is created by browser each time we enter website then it removes.i disabled caching but still shows.When i delete session cookie from browser then the problem solves.is this bug or what?
2
Answers
simply instead of using put u can use flash method after remove cookie from your browser.
As far as I know, laravel use to put session to cookie, Laravel uses a server-side session driver.
When you set a session value using
the session data is stored on the server. However, the session cookie on the client side may still have the old session data cached. This is why you are seeing the old session message even after removing it from your code or restarting the PHP server.
To ensure that the session data is updated on the client side, you can use the
session()->flash()
method instead ofsession()->put()
. Theflash()
method only stores the session data for the next request and then automatically removes it, ensuring that the client-side session cookie is updated.for example:
or in other way, you could also do something like this
it would gives you more control over the data and allows you to persist it across multiple requests if needed. This can be useful if you want to display dynamic data that persists throughout the user’s session or across different pages.