logo
podcast Podcast
get help Get Unstuck

Be precise when clearing session values

Easier to read and safer too

Joel Clermont
Joel Clermont
2025-06-06

In a multistep workflow, we will often use the session to store some details about the user's progress. And when you get to the end of the workflow, those session values are cleared out to reset the workflow to its initial state.

And session usage tends to be lighter in a modern Laravel app than the old vanilla PHP app of years past. So the only values in the session might be the one or two you're using for the workflow.

As a result, the tendency might be to just clear the session entirely.

This works, but I want to make the case for being more precise and only clearing the specific values you need to clear.

Let's start by comparing the two approaches in code:

// option 1: clear everything from the session
session()->flush();

// option 2: clear only the values this workflow uses
session()->forget([
    SessionKey::WORKFLOW_COMPLETED,
    SessionKey::WORKFLOW_DATA,
]);

If the only two session values in use are the ones for the workflow, then these two options will have the same effect.

But, I would argue that option 2 is still more readable. We can see exactly what we are clearing without having to review the rest of the workflow code. And as a bonus tip, we like using constants for session keys instead of bare strings, making it easier to find usage throughout the application.

Finally, option 2 is safer. Who is to say that weeks or months from now, there won't be some unrelated piece of code that also puts data in the session? If we forget that, and the user goes through this workflow, we've now just introduced a bug.

For those reasons, I recommend always being precise when clearing session values.

Being explicit tends to be reliable programming advice in general. This is just one concrete example of that principle.

Here to help,

Joel

P.S. Would you benefit from having two experienced Laravel developers review your code and give you feedback? Get some piece of mind and contact us to schedule a code review.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.