0

我正在开发一个仅使用 API 路由的 Laravel 5 应用程序。我创建了一个宏来扩展响应助手的添加 cookie 方法。但是我遇到了我的宏不存在的错误。

我们使用它来返回响应:

return response()->json($data, $status)
  ->cookie(
     'COOKIE_NAME',
     $value,
     $expiration,
     '/',
     app()->environment('production') ? config('app.domain') : null,
     app()->environment('production'),
     true
  );

由于过期后的数据对于所有带有 cookie 的端点总是相同的,我想创建一个宏,该宏会自动将该数据添加到 cookie 并将代码简化为:

return response()->json($data, $status)
  ->httpCookie('COOKIE_NAME, $value, $expiration);

我已经创建了一个并添加了使用方法ResponseServiceProvider的宏。Response::macro

这是我的宏代码:

public function boot()
{
  Response::macro('httpCookie', function ($name, $value, $expiration) {
    $isProd = app()->environment('production');
    return response()->cookie(
      $name, 
      $value,
      $expiration,
      '/',
      $isProd ? config('app.domain') : null,
      $isProd,
      true
    );
  });
}

然后尝试测试端点,我遇到了一个错误:

BadMethodCallException
Method Illuminate\Http\JsonResponse::httpCookie does not exist.

我怎么解决这个问题?谢谢。

4

1 回答 1

1

当我查看Illuminate\Support\Facades\Response类时,Response Facade 代理了Illuminate\Routing\ResponseFactory类。尽管 ResponseFactory 也是可宏的,但它用于不同的目的。

所以请向正确的类添加一个宏,在这种情况下,我认为Illuminate\Http\Response

use Illuminate\Http\Response;

public function boot()
{
  Response::macro('httpCookie', function ($name, $value, $expiration) {
    $isProd = app()->environment('production');
    return $this->cookie(
      $name, 
      $value,
      $expiration,
      '/',
      $isProd ? config('app.domain') : null,
      $isProd,
      true
    );
  });
}

于 2019-07-12T12:37:02.247 回答