每个请求都有响应。laravel提供了几种不同的方法来返回响应。响应可以是来自路由或控制器发送。发送基本响应 - 如在下面示例代码所示出的简单字符串。该字符串将被自动转换为相应的http响应。
app/http/routes.php
route::get('/basic_response', function () { return 'hello world'; });
http://localhost:8000/basic_response
响应可以使用header()方法附加到头。我们还可以将一系列报头添加,如下示例代码所示。
return response($content,$status) ->header('content-type', $type) ->header('x-header-one', 'header value') ->header('x-header-two', 'header value');
app/http/routes.php
route::get('/header',function(){ return response("hello", 200)->header('content-type', 'text/html'); });
http://localhost:8000/header
withcookie()辅助方法用于附加 cookies。使用这个方法生成的 cookie 可以通过调用withcookie()方法响应实例附加。缺省情况下,通过laravel 生成的所有cookie被加密和签名,使得它们不能被修改或由客户端读取。
app/http/routes.php
route::get('/cookie',function(){ return response("hello", 200)->header('content-type', 'text/html') ->withcookie('name','virat gandhi'); });
http://localhost:8000/cookie
json响应可以使用 json 方法发送。这种方法会自动设置content-type头为application/json。json的方法将数组自动转换成合适的json响应。
app/http/routes.php
route::get('json',function(){ return response()->json(['name' => 'h3', 'state' => 'hainan']); });
http://localhost:8000/json