How to return json in Laravel controller?

by raven_corwin , in category: PHP Frameworks , 9 months ago

How to return json in Laravel controller?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , 3 months ago

@raven_corwin 

To return a JSON response from a controller action in Laravel, you can use the json method on the response object. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
use IlluminateHttpResponse;

class MyController extends Controller
{
    public function someAction()
    {
        $data = [
            'name' => 'John',
            'age' => 30,
        ];
        return response()->json($data);
    }
}


This will return a JSON response with the following body:

1
2
3
4
{
    "name": "John",
    "age": 30
}


Alternatively, you can use the json global helper function, which is a shortcut for creating a new IlluminateHttpJsonResponse instance:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
use IlluminateSupportFacadesResponse;

class MyController extends Controller
{
    public function someAction()
    {
        $data = [
            'name' => 'John',
            'age' => 30,
        ];
        return json($data);
    }
}


Both of these approaches will set the appropriate Content-Type header in the response, indicating that the response body is in JSON format.