I can't figure out how to how to add headers to a response from a middleware. I've used both ->header(...) and ->headers->set(...) but both gives errors. So how do you do it?

首先我试着

public function handle($request, Closure $next) {
    $response = $next($request);

    $response->headers->set('refresh', '5;url=' . route('foo'));

    return $response;
}

这和Illuminate\Http\Middleware\FrameGuard.php年时一样,但这给了

Call to a member function set() on a non-object

Second I tried with

public function handle($request, Closure $next) {
    $response = $next($request);

    $response->header('refresh', '5;url=' . route('foo'));

    return $response;
}

但这给了

视图上不存在方法[Header].

那么,如何从中间件添加标头呢?

推荐答案

I solved this by using the response helper.

use Illuminate\Http\RedirectResponse;

$response = $next($request);
$response = $response instanceof RedirectResponse ? $response : response($response);

return $response->header('refresh', '5;url=' . route('foo'));

我的所有其他中间件似乎都能很好地运行,所以我想它很好.

Laravel相关问答推荐

try 编写一个函数,如果产品存在,则无法删除特定类别

查询Laravel中的图形

Laravel 9 上的数组差异助手

使用Laravel Blade Formatter和PHP Intelephense进行 VSCode 格式化

Eloquent的条件过滤器

Laravel 不验证是否不需要字段

.gitignore 不忽略文件夹

Heroku 上的 Laravel 队列工作者

Laravel - 验证 - 如果字段为空则需要

Laravel 从现有模型生成迁移

Eloquent 的 Model::query() 是什么意思?

如何从 Windows 命令提示符在 Laravel 中运行 PHPUnit

加载模型的所有关系

如何在 Laravel 5 中按键获取所有缓存项目的列表?

在 Laravel 中,如何获取 *only* POST 参数?

Laravel:方法[显示]不存在

在 Laravel 中结合 AND/OR Eloquent的查询

使用哪个 Auth::check() 或 Auth::user() - Laravel 5.1?

开发中的 Laravel 和视图缓存 - 无法立即看到更改

Eloquent的关系 - attach附加(但不保存)到 Has Many