[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
- 任務調度
- 測試
- 驗證
- 新手入門指南
- 簡單任務管理系統
- 帶用戶功能的任務管理系統