Home  >  Article  >  Backend Development  >  Laravel如何返回JSON数据?

Laravel如何返回JSON数据?

PHPz
PHPzOriginal
2016-06-06 20:32:253628browse

Laravel如何返回JSON数据?

 Laravel如何返回 JSON 数据?

在控制器或者闭包路由里,如果返回数组或者模型(或者集合)的话,Laravel 会自动识别并自动转为 json 响应:

// 直接返回数组
Route::get('/request-json-array', function(){
    $array = array('foo', 'bar');
    // 返回的就是 json 响应
    return $array;
});
// 或者返回模型/集合
Route::get('/request-json-model', function(){
    // User 是  eloquent 模型
    return User::all();
});

或者可以使用以下方法:

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

使用 ->json() 的好处是可以自定义更多的响应信息,如状态码、头信息等。json() 方法的定义如下:

/**
* 返回一个新的 JSON 响应
*
* @param string|array $data
* @param int $status
* @param array $headers
* @param int $options
* @return \Symfony\Component\HttpFoundation\Response 
* @static 
*/
public static function json($data = array(), $status = 200, $headers = array(), $options = 0){
    return \Illuminate\Routing\ResponseFactory::json($data, $status, $headers, $options);
}

更多相关知识,请访问PHP中文网

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn