Laravel函数不读取$ id

问题描述 投票:0回答:1

在我的Web应用程序中,我添加了缓存方法。但是问题是它没有读取传递给函数的指定的$ id。这样它的抛出错误就象:

ErrorException:未定义的变量:id

如果有人提出任何答案将很有帮助。

这里是代码->

public function relatedstory($id)
    {
        $key = $id;

        $cacheKey = $this->getCacheKey($key);

        return cache()->remember($cacheKey, Carbon::now()->addDay(1), function ()
        {
            $story = $this->_story->findOrFail($id);
            $tags = $story->tags->random(1)->pluck('tag_id');
            $storyIds = StoryTagItem::whereTagId($tags)->get()->random(4)->pluck('story_tag_id');
            $relatedStory = [];
            foreach($storyIds as $storyId)
            {
                array_push($relatedStory, $this->_story->findOrFail($storyId));
            }
            return StoryListResource::collection($relatedStory);
        });
    }
php laravel laravel-5
1个回答
0
投票

您需要function() use ($id)才能将$id注入关闭。

return cache()->remember($cacheKey, Carbon::now()->addDay(1), function () use ($id)
        {
 ...
        });
© www.soinside.com 2019 - 2024. All rights reserved.