php - How does laravel return json data elegantly?
我想大声告诉你
我想大声告诉你 2017-05-27 17:43:42
0
5
736

For example:


class TestController extends Controller
{
    public function index() {
        $arr = [1,2];
        return json_encode($arr);
    } 
}

Is there any way to automatically perform the json_encode operation when returning without requiring each function to manually perform the json_encode operation?

Additional explanation: What I mean is that jsone_encode() does not need to be explicitly specified in the return line, which means that response()->json() in laravel is also explicitly specified. This method is not the result I want. .

Solved:
I didn’t read the document carefully.
Just return the array directly.
return $arr;
return json_encode($arr);
The difference is:
The Content-Type of the former’s http Response Headers is application/json
The latter’s http Response Headers are Content-Type is text/html;

For the client, pay attention to the difference here.

我想大声告诉你
我想大声告诉你

reply all(5)
漂亮男人

Return array directly

Not reading the document carefully

Documentation

我想大声告诉你

You can use third-party packages, for example, you can check out this tutorial

Use laravel+dingo to create your RESTful interface

Return method

    return $this->response->array(['msg'=>$msg]);
世界只因有你

It is better to rely on the heaven, the earth, and the people than rely on official documents
https://docs.golaravel.com/do...

Ty80

Return in laravel will automatically convert the data into a json string

滿天的星座

http://d.laravel-china.org/do...

return response()->json([
    'name' => 'Abigail',
    'state' => 'CA'
]);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template