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

skegel13's avatar

Using tap() to set item on session

I want retrieve a session variable and if it doesn't exist, get a value and set it on the session.

I have a users table and comments table. I want to loop through each user and manipulate comments in the system. So I am not pulling the comments out of the database each time for the users, I wanted to just store them all in the session.

If I have a function on my users model like:

public function doStuffWithComments() {
    $comments = session()->get(
        'comments', 
        tap(Comment::get(), function ($comments) { 
            session()->put('users', $users);
        }
    );

    // Do stuff with comments
}

Then for my users, I want to do something like:

Users:get()->each(function ($user) {
    $user->doStuffWithComments();
});

However, everytime I call that method, it is pulling the comments out of the database again instead of using the session. I'm guessing it has something to do with it being used in a callback.

Any ideas?

0 likes
1 reply
JackJones's avatar

It seems to not make sense to me, maybe I'm daft but why would something so simple need to be so complicated?

if(!session('comments'))
    session(['comments' => Comment::get());

Please or to participate in this conversation.