php - Laravel 分形转换器,如何传递和获取额外变量

标签 php laravel laravel-5.2

我正在使用 Dingo API 在 Laravel 5.2 中创建 API 并让 Controller 返回数据

 return $this->response->paginator($rows, new SymptomTransformer, ['user_id' => $user_id]);

但是,我不知道如何在 SymptomTransformer 中检索 user_id 值!尝试了许多不同的方法并尝试研究类(class),但我对 Laravel 和 OOP 都比较陌生,所以如果有人能指出我正确的方向,我将不胜感激。

下面是我的转换器类。

class SymptomTransformer extends TransformerAbstract
{
    public function transform(Symptom $row)
    {  
        // need to get user_id here
        return [
            'id' => $row->id,
            'name' => $row->name,
            'next_type' => $next,
            'allow' => $allow
        ];
    }
}

最佳答案

您可以将额外的参数传递给转换器构造函数。

class SymptomTransformer extends TransformerAbstract
{
     protected $extra;

     public function __construct($extra) {
         $this->extra = $exta;
     }

      public function transform(Symptom $row)
      {  
         // need to get user_id here
         dd($this->extra);
         return [
            'id' => $row->id,
            'name' => $row->name,
            'next_type' => $next,
            'allow' => $allow
        ];
      }
}

然后调用

return $this->response->paginator($rows, new SymptomTransformer(['user_id' => $user_id]));

关于php - Laravel 分形转换器,如何传递和获取额外变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41595129/

相关文章:

laravel - 路由存在 - 测试认为它不存在

php - Magento 1.5 Paypal Express 评论页面运输 - 没有可用的报价

namespaces - 输入中的意外字符 : '\' (ASCII=92) state=1 in a Silex Application

php - 结合 HTTP 身份验证和 PHP session ?

laravel - 如果用户未使用 Laravel 5.4 登录,则限制对页面的访问

php - Laravel View 链接和 web.php 路由搞砸了

php - 在 PHP 按钮代码中设置默认值

laravel - 如何在Laravel 5.3中获取当前语言环境

php - 如何: migration many-to-many laravel artisan

php - Laravel - 不允许用户访问其他用户数据