Yesterday, I was talking about whether flushing a session would log you out, and digging into a couple scenarios.
While we were diving into how sessions are used in Laravel, there were a few other session-related features I wanted to discuss today.
Let's start by looking at a very typical output for session()->all()
in a Laravel app:
[
"_token" => "9jqdNux1iJR5Z8WpqkPohUR0RkNltfCFsiLgQV9x",
"login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d" => 4832,
"_previous" => ["url" => "https://some-project.local"],
"_flash" => ["old" => [], "new" => []]
]
In our last tip, we discussed the login_web_*
key, which is used by the SessionGuard
to track the currently logged-in user.
But what are these other keys?
The _token
key is used for CSRF protection.
Laravel automatically generates this token and includes it in forms to ensure that the form submission is coming from your application.
Any form submissions then compare the token to what is stored in the session.
So if you wipe this key, and then try to POST
a form, you will get a 419
error because the CSRF token will not match.
The _previous
key is used to store the URL of the previous request.
This could be used to redirect()->back()
to the last page, or redirect()->intended()
to go back to the page they were on before being redirected to a login page.
These features would also break if you flush the session.
The last one is _flash
, which is used to store flash messages.
In addition to explicit messages you set, this also includes data the user originally submitted when their request fails validation.
If you flush the session, you will lose all of these keys and their values, breaking some key Laravel features your app likely relies on.
I probably already made the point in the first tip, but this was a nice excuse to explore how Laravel works with sessions and help you understand it a bit better.
Here to help,
Joel
P.S. Programming involves tradeoffs and there isn't always a clear answer as to what is the best way to do something. That's why it is valuable to get a variety of opinions in the Mastering Laravel community.