search

Home  >  Q&A  >  body text

php - How does laravel return json data elegantly?

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.

我想大声告诉你我想大声告诉你2755 days ago745

reply all(5)I'll reply

  • 漂亮男人

    漂亮男人2017-05-27 17:45:42

    Return array directly

    Not reading the document carefully

    Documentation

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-05-27 17:45:42

    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]);

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-27 17:45:42

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

    reply
    0
  • PHP中文网

    PHP中文网2017-05-27 17:45:42

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

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-27 17:45:42

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

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

    reply
    0
  • Cancelreply