Laravel回應

基本回應

每個請求都有回應。Laravel提供了幾種不同的方法來返回回應。回應可以是來自路由或控制器發送。發送基本回應 - 如在下面示例代碼所示出的簡單字串。該字串將被自動轉換為相應的HTTP回應。

示例

第1步 -將下麵的代碼添加到 app/Http/routes.php 檔。

app/Http/routes.php

Route::get('/basic_response', function () {
   return 'Hello World';
});
第2步 - 訪問以下網址進行測試的基本回應。

http://localhost:8000/basic_response

第3步 - 輸出結果如下圖所示。

附加頭

回應可以使用header()方法附加到頭。我們還可以將一系列報頭添加,如下示例代碼所示。

return response($content,$status)
   ->header('Content-Type', $type)
   ->header('X-Header-One', 'Header Value')
   ->header('X-Header-Two', 'Header Value');

示例

第1步 -下麵的代碼添加到 app/Http/routes.php 檔。

app/Http/routes.php

Route::get('/header',function(){
   return response("Hello", 200)->header('Content-Type', 'text/html');
});
第2步 - 訪問以下網址進行測試的基本回應。

http://localhost:8000/header

第3步 - 輸出結果如下圖所示。

附加Cookies

withcookie()輔助方法用於附加 cookies。使用這個方法生成的 cookie 可以通過調用withcookie()方法回應實例附加。缺省情況下,通過Laravel 生成的所有cookie被加密和簽名,使得它們不能被修改或由客戶端讀取。

示例

第1步 -下麵的代碼添加到 app/Http/routes.php 檔。

app/Http/routes.php

Route::get('/cookie',function(){
   return response("Hello", 200)->header('Content-Type', 'text/html')
      ->withcookie('name','Virat Gandhi');
});
第2步 - 訪問以下網址進行測試的基本回應。

http://localhost:8000/cookie

第3步 - 輸出結果如下圖所示。

JSON回應

JSON回應可以使用 json 方法發送。這種方法會自動設置Content-Type頭為application/json。JSON的方法將數組自動轉換成合適的JSON回應。

示例

第1步 -添加下麵一行到檔 - app/Http/routes.php。

app/Http/routes.php

Route::get('json',function(){
   return response()->json(['name' => 'zaixian', 'state' => 'Hainan']);
});
第2步 - 訪問以下網址測試JSON回應。

http://localhost:8000/json

第3步 - 輸出結果如下圖所示。


上一篇: Laravel Cookie 下一篇: Laravel視圖