Skip to content

Laravel - 响应

所有路由(routes)和控制器(controllers)都应该返回一个响应(response),该响应将发送回用户的浏览器。Laravel 提供了几种不同的方式来返回响应。最基本的响应是直接从路由或控制器返回一个字符串。Laravel 会自动将该字符串转换为一个完整的 HTTP 响应。

最简单的响应是从路由或控制器返回一个字符串。Laravel 会自动将此字符串转换为适当的 HTTP 响应。

步骤 1: 将以下代码添加到您的 routes/web.php 文件中。

routes/web.php

Route::get('/greeting', function () {
return 'Hello World';
});

步骤 2: 在浏览器中访问 http://localhost:8000/greeting。

步骤 3: 浏览器将显示文本 ‘Hello World’。

然而,对于大多数操作,您将返回一个完整的 Illuminate\Http\Response 实例或一个视图(view)。返回一个完整的 Response 实例允许您自定义响应的 HTTP 状态码和头信息(headers)。

一个 Response 实例继承自 Symfony\Component\HttpFoundation\Response 类,该类提供了多种用于构建 HTTP 响应的方法。

return response('Hello World', 200)
->header('Content-Type', 'text/plain');

请记住,大多数响应方法都是可链式调用的(chainable),允许流畅地构建响应。例如,您可以使用 header 方法在将响应发送回用户之前,为响应添加一系列头信息:

return response($content, 200)
->header('Content-Type', 'application/json')
->header('X-Header-One', 'Header Value')
->header('X-Header-Two', 'Another Header Value');

示例:带有自定义头信息的响应

Section titled “示例:带有自定义头信息的响应”

步骤 1: 将以下代码添加到 routes/web.php 中。

routes/web.php

Route::get('/custom-header', function() {
return response("Response with custom header", 200)
->header('Content-Type', 'text/plain')
->header('X-Custom-Info', 'Laravel Tutorial');
});

步骤 2: 访问 http://localhost:8000/custom-header。

步骤 3: 浏览器将显示 ‘Response with custom header’。如果您使用浏览器开发者工具检查响应头信息,您将看到 Content-Type: text/plain 和 X-Custom-Info: Laravel Tutorial。

您可以使用 withCookie 方法将一个 cookie 附加到 Illuminate\Http\Response 实例。您应该传递 cookie 实例,该实例可以使用全局的 cookie 辅助函数生成。

use Illuminate\Http\Request;
Route::get('/set-cookie', function (Request $request) {
$cookie = cookie('my_cookie_name', 'my_cookie_value', 60); // 60 minutes
return response('Cookie has been set!', 200)->withCookie($cookie);
});

默认情况下,Laravel 生成的所有 cookie 都是加密并签名的,以便客户端无法修改或读取它们。如果您想禁用应用程序生成的部分 cookie 的加密,您可以使用 App\Http\Middleware\EncryptCookies 中间件的 $except 属性,该中间件位于 app/Http/Middleware 目录中。

步骤 1: 将以下路由添加到 routes/web.php 中。

routes/web.php

Route::get('/set-user-cookie', function() {
return response("Hello with Cookie!", 200)
->header('Content-Type', 'text/html')
->withCookie(cookie('user_preference', 'dark_mode', 120)); // Cookie for 120 minutes
});

步骤 2: 访问 http://localhost:8000/set-user-cookie。

步骤 3: 浏览器将显示 ‘Hello with Cookie!’。使用浏览器开发者工具,您可以检查 cookie 并找到设置为 dark_mode 值(加密后)的 user_preference。

json 方法将自动设置 Content-Type 头为 application/json,并使用 PHP 的 json_encode 函数将给定的数组转换为 JSON:

return response()->json([
'name' => 'Abigail',
'state' => 'CA'
]);

如果您想创建一个 JSONP 响应,您可以结合使用 json 方法和 withCallback 方法:

return response()
->json(['name' => 'Abigail', 'state' => 'CA'])
->withCallback($request->input('callback'));

步骤 1: 在 routes/web.php 中添加以下路由。

routes/web.php

Route::get('/api/user', function() {
return response()->json(['id' => 1, 'name' => 'Jane Doe', 'email' => 'jane@example.com']);
});

步骤 2: 访问 http://localhost:8000/api/user。

步骤 3: 浏览器将显示 JSON 字符串:{"id":1,"name":"Jane Doe","email":"jane@example.com"}。

其他响应类型包括视图响应(View Responses)、文件下载(File Downloads)和重定向(Redirects),每种类型都有其特定的辅助方法。有关详细信息,请参阅官方 Laravel 文档中关于 HTTP 响应的部分。