简体   繁体   English

在Laravel 5中为与json方法链接的响应助手添加宏时出错

[英]Error on adding macro for response helper chained with json method in Laravel 5

I'm working on a Laravel 5 Application that only uses API routes. 我正在使用仅使用API​​路由的Laravel 5应用程序。 I created a macro to extend the add cookie method of the response helper. 我创建了一个宏来扩展响应助手的添加cookie方法。 But I encountered an error that my macro doesn't exist. 但是我遇到一个错误,说我的宏不存在。

We are using this for returning response: 我们使用它来返回响应:

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

as the data beyond the expiration is always the same for all endpoint with cookie, I want to create a macro that will automatically adds that data to the cookie and reduce the code to this: 由于过期后的数据对于所有使用cookie的端点而言始终是相同的,因此我想创建一个宏,该宏将自动将该数据添加到cookie中并减少代码:

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

I have created a ResponseServiceProvider and add the macro using Response::macro method. 我已经创建了ResponseServiceProvider并使用Response::macro方法添加了宏。

Here is my macro code: 这是我的宏代码:

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
    );
  });
}

Then trying to test the endpoint, I ran to an error: 然后尝试测试端点,我遇到了一个错误:

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

How can I solve this problem? 我怎么解决这个问题? Thanks. 谢谢。

When I look at the Illuminate\\Support\\Facades\\Response class, the Response Facade proxies the Illuminate\\Routing\\ResponseFactory class. 当我查看Illuminate \\ Support \\ Facades \\ Response类时,响应外观将代理Illuminate \\ Routing \\ ResponseFactory类。 Though the ResponseFactory is also macroable, it is used for a different purpose. 尽管ResponseFactory也可以宏化,但它用于其他目的。

So please add a macro to the correct class, in this case I think Illuminate\\Http\\Response : 因此,请将宏添加到正确的类中,在这种情况下,我认为是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
    );
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM