[TOC]
### **1、基本[响应](http://laravelacademy.org/tags/%e5%93%8d%e5%ba%94 "View all posts in 响应")**
所有[路由](http://laravelacademy.org/tags/%e8%b7%af%e7%94%b1 "View all posts in 路由")和控制器都会返回某种被发送到用户浏览器的响应,[Laravel](http://laravelacademy.org/tags/laravel "View all posts in Laravel") 提供了多种不同的方式来返回响应,最基本的响应就是从路由或控制器返回一个简单的字符串:
~~~
Route::get('/', function () {
return 'Hello World';
});
~~~
给定的字符串会被框架自动转化为 [HTTP](http://laravelacademy.org/tags/http "View all posts in HTTP") 响应。
#### **[Response](http://laravelacademy.org/tags/response "View all posts in Response") 对象**
然而,大多数路由和控制器动作都会返回一个完整的 `Illuminate\Http\Response` 实例或[视图](http://laravelacademy.org/tags/%e8%a7%86%e5%9b%be "View all posts in 视图"),返回一个完整的 Response 实例允许你自定义响应的 HTTP 状态码和头信息。Response 实例继承自`Symfony\Component\HttpFoundation\Response` 类,该类提供了一系列方法用于创建 HTTP 响应:
~~~
use Illuminate\Http\Response;
Route::get('home', function () {
return (new Response($content, $status))
->header('Content-Type', $value);
});
~~~
为方便起见,还可以使用辅助函数 `response`:
~~~
Route::get('home', function () {
return response($content, $status)
->header('Content-Type', $value);
});
~~~
> 注:查看完整的 Response 方法列表,请移步相应的 [API 文档](http://laravel.com/api/master/Illuminate/Http/Response.html) 以及 [Symfony API 文档](http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/Response.html)。
#### **添加响应头**
大部分响应方法都是可以以方法链形式调用的,从而使得可以平滑的构建响应(流接口模式)。例如,可以使用`header` 方法来添加一系列响应头:
~~~
return response($content)
->header('Content-Type', $type)
->header('X-Header-One', 'Header Value')
->header('X-Header-Two', 'Header Value');
~~~
或者你可以使用 `withHeaders` 方法来指定头信息数组并添加到响应:
~~~
return response($content)
->withHeaders([
'Content-Type' => $type,
'X-Header-One' => 'Header Value',
'X-Header-Two' => 'Header Value',
]);
~~~
#### **添加 [Cookie](http://laravelacademy.org/tags/cookie "View all posts in Cookie") 到响应**
使用响应实例的辅助函数 `cookie` 可以轻松添加 Cookie 到响应:
~~~
return response($content)->header('Content-Type', $type)
->cookie('name', 'value');
~~~
`cookie` 方法接收额外的可选参数从而允许对 Cookie 属性进行更多的自定义:
~~~
->cookie($name, $value, $minutes, $path, $domain, $secure, $httpOnly)
~~~
默认情况下,Laravel 框架生成的 Cookie 经过了加密和签名,以免在客户端被篡改。如果你想要让特定的 Cookie 子集在生成时取消加密,可以使用中间件 `App\Http\Middleware\EncryptCookies` 的 `$except` 属性来排除这些 Cookie:
~~~
/**
* 不需要被加密的cookies名称
*
* @var array
*/
protected $except = [
'cookie_name',
];
~~~
### **2、其它响应类型**
辅助函数 `response` 可以很方便地用来生成其他类型的响应实例,当无参数调用 `response` 时会返回`Illuminate\Contracts\Routing\ResponseFactory` 契约的一个实现类实例,该契约提供了一些有用的方法来生成响应。
#### **视图**
如果你需要控制响应状态和响应头,并且还需要返回一个视图作为响应内容,可以使用 `view` 方法:
~~~
return response()->view('hello', $data)->header('Content-Type', $type);
~~~
当然,如果你不需要传递自定义的 HTTP 状态码和头信息,只需要简单使用全局辅助函数 `view` 即可。
#### **[JSON](http://laravelacademy.org/tags/json "View all posts in JSON")**
`json` 方法会自动将 Content-Type 头设置为 `application/json`,并使用 PHP 函数 `json_encode` 方法将给定数组转化为 JSON:
~~~
return response()->json(['name' => 'Abigail', 'state' => 'CA']);
~~~
如果你想要创建一个 [JSONP](http://laravelacademy.org/tags/jsonp "View all posts in JSONP") 响应,可以在 `json` 方法之后调用 `setCallback` 方法:
~~~
return response()->json(['name' => 'Abigail', 'state' => 'CA'])
->setCallback($request->input('callback'));
~~~
#### **[文件下载](http://laravelacademy.org/tags/%e6%96%87%e4%bb%b6%e4%b8%8b%e8%bd%bd "View all posts in 文件下载")**
`download` 方法用于生成强制用户浏览器下载给定路径文件的响应。`download` 方法接受文件名作为第二个参数,该参数决定用户下载文件的显示名称,你还可以将 HTTP 头信息作为第三个参数传递到该方法:
~~~
return response()->download($pathToFile);
return response()->download($pathToFile, $name, $headers);
~~~
> 注意:管理文件下载的 Symfony HttpFoundation 类要求被下载文件有一个 ASCII 文件名。
### **3、[重定向](http://laravelacademy.org/tags/%e9%87%8d%e5%ae%9a%e5%90%91 "View all posts in 重定向")**
重定向响应是 `Illuminate\Http\RedirectResponse` 类的实例,其中包含了必须的头信息将用户重定向到另一个 URL,有很多方式来生成 `RedirectResponse` 实例,最简单的方法就是使用全局辅助函数 `redirect`:
~~~
Route::get('dashboard', function () {
return redirect('home/dashboard');
});
~~~
有时候你想要将用户重定向到上一个请求的位置,比如,表单提交后,验证不通过,你就可以使用辅助函数 `back` 返回到前一个 URL(使用该方法之前确保路由使用了 `web` 中间件组或者都使用了 `session` 中间件):
~~~
Route::post('user/profile', function () {
// 验证请求...
return back()->withInput();
});
~~~
#### **重定向到命名路由**
如果调用不带参数的 `redirect` 方法,会返回一个 `Illuminate\Routing\Redirector` 实例,然后可以调用该实例上的任何方法。比如,为了生成一个 `RedirectResponse` 到命名路由,可以使用 route 方法:
~~~
return redirect()->route('login');
~~~
如果路由中有参数,可以将其作为第二个参数传递到 `route` 方法:
~~~
// For a route with the following URI: profile/{id}
return redirect()->route('profile', [1]);
~~~
如果要重定向到带 ID 参数的路由( Eloquent 模型绑定 ),可以传递模型本身,ID 会被自动解析出来:
~~~
return redirect()->route('profile', [$user]);
~~~
#### **重定向到控制器动作**
你还可以生成重定向到控制器动作,只需简单传递控制器和动作名到 `action` 方法即可。记住,你不需要指定控制器的完整命名空间,因为 Laravel 的 `RouteServiceProvider` 将会自动设置默认的控制器命名空间:
~~~
return redirect()->action('HomeController@index');
~~~
当然,如果控制器路由要求参数,你可以将参数作为第二个参数传递给 `action` 方法:
~~~
return redirect()->action('UserController@profile', [1]);
~~~
#### **带一次性 [Session](http://laravelacademy.org/tags/session "View all posts in Session") 数据的重定向**
重定向到一个新的 URL 并将数据存储到一次性 Session 中通常是同时完成的,为了方便,可以创建一个`RedirectResponse` 实例然后在同一个方法链上将数据存储到 Session,这种方式在 action 之后存储状态信息时特别方便:
~~~
Route::post('user/profile', function () {
// 更新用户属性...
return redirect('dashboard')->with('status', 'Profile updated!');
});
~~~
当然,用户重定向到新页面之后,你可以从 Session 中取出并显示这些一次性信息,比如,使用 Blade 语法实现如下:
~~~
@if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
@endif
~~~
### **4、响应宏**
如果你想要定义一个自定义的响应并且在多个路由和控制器中复用,可以使用`Illuminate\Contracts\Routing\ResponseFactory` 实现类或者 `Response` 门面上的 `macro` 方法。
比如,在某个服务提供者的 boot 方法中编写代码如下:
~~~
<?php
namespace App\Providers;
use Response;
use Illuminate\Support\ServiceProvider;
class ResponseMacroServiceProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
Response::macro('caps', function ($value) {
return Response::make(strtoupper($value));
});
}
}
~~~
`macro` 方法接收响应名称作为第一个参数,闭包函数作为第二个参数,`macro` 的闭包在 `ResponseFactory` 实现类或辅助函数 `response` 中调用 `macro` 名称的时候被执行:
~~~
return response()->caps('foo');
~~~
- 序言
- 发行版本说明
- 升级指南
- 贡献代码
- 开始
- 安装
- 配置
- Laravel Homestead
- 基础
- HTTP 路由
- HTTP 中间件
- HTTP 控制器
- HTTP 请求
- HTTP 响应
- 视图
- Blade 模板引擎
- 架构
- 一次请求的生命周期
- 应用目录结构
- 服务提供者
- 服务容器
- 门面(Facades)
- 数据库
- 起步
- 查询构建器
- 迁移
- 填充数据
- Eloquent ORM
- 起步
- 关联关系
- 集合
- 访问器&修改器
- 序列化
- 服务
- 用户认证
- 用户授权
- Artisan Console
- 订阅支付实现:Laravel Cashier
- 缓存
- 集合
- 集成前端资源:Laravel Elixir
- 加密
- 错误&日志
- 事件
- 文件系统/云存储
- 哈希
- 辅助函数
- 本地化
- 邮件
- 包开发
- 分页
- Redis
- 队列
- Session
- Envoy Task Runner
- 任务调度
- 测试
- 验证
- 新手入门指南
- 简单任务管理系统
- 带用户功能的任务管理系统