如何在laravel中缓存函数的结果

I would like to know if it is possible to store the results of a function in cache for each possible outcome.

This is not an exact example below, the real example is a lot more complex and I need to cache the results for speed reasons, but this gives you an idea of what I'm trying to accomplish

For example I have a function that retrieves the users comments:

public function getUserComments(User $user)
{
    $comments = DB::table('comments')->where('user_id',$user->id)->get();
    return $comments;
}

I need to save all the possible outcomes for each individual user in my system so essentially.

For example if I have 100 users:

foreach ($users as $user) {
       $cachedResults [] = $user->getUserComments();
}

Now I have the cached results that are faster to look through: $cachedResults

Something like this should do the trick(not tested):

public function getUserComments(User $user)
{
    $key = "comments-${$user->id}";

    $comments = Cache::remember($key, 60, function () {
        return DB::table('comments')->where('user_id',$user->id)->get();
    });

    return $comments
}

60 is the amount of minutes here. You have to configure your cache if you want something other than the default, which is the file cache driver.

I agree with Stephan answer, you may save the value with a specific key or, you can use tags, something like:

Cache::tags(['users', $name])->remember('model', 60, function () {
    // [...]
});

I prefer this second approach because it's easiear to manage if you make some changes on your database...

For example you can use the ['users', $name] tags in order to store multiple keys that refers to a specific user, for example the comments relation.

When you make a change to the user model, you will only refresh the ['users', $name] tags with 'model' key.

If you delete the user, you will flush the ['users', $name] tags and if you perform a mass delete, you will flush the users tag in order to clear all the stored users in cache.

Of course you have to use the cache drivers that allow tags.