php - Laravel Cache,闭包内的变量未定义?

标签 php laravel laravel-5

我有这样一个函数:

public function entity($entity_id, Request $request)
{
    $expiresAt = Carbon::now()->addMinutes(10);
    $entity = Cache::remember('entities', $expiresAt, function () {
        return Entity::where('id', $entity_id)
            ->with('address')
            ->with('_geoloc')
            ->first();
    });

然而,这会返回一个错误,指出 $entity_id 未定义,但是当我在 $expiresAt 之后执行 dd($entity_id) 时,它在我取回 id 时被定义,如果需要,id 来自 url。

最佳答案

您应该允许匿名函数捕获作用域外的变量。 $entity_id 它在范围之外。这就是 php 表达闭包的方式。使用 use() 会起作用。

public function entity($entity_id, Request $request)
{
$expiresAt = Carbon::now()->addMinutes(10);
$entity = Cache::remember('entities', $expiresAt, function () use($entity_id) {
    return Entity::where('id', $entity_id)
        ->with('address')
        ->with('_geoloc')
        ->first();
});

关于php - Laravel Cache,闭包内的变量未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46912152/

相关文章:

php - Laravel - 选择多对多关系的特定列

php - 通过多态使用 Laravel Eloquents HasManyThrough 关系与多个关系

php - 如何在 laravel 中使用 IF(expression, value_if_true,value_if_false) 创建条件查询?

PHP 多页面点击计数器自动生成

Tomcat 8 上的 PHP

PHP DOM loadHTML() 方法异常警告

php - 带有未转义 html 的 Laravel laravelcollective/html textarea

php - 检查 Laravel 包服务提供者中是否存在迁移

laravel - 从Laravel中的通知数据库中提取数据

php - Laravel 验证 - 禁止请求参数的规则