How to return Json Laravel

Laravel: Learn how to return a JSON response & see a practical example.

Returning Json in Laravel

Laravel makes it easy to return JSON responses from your application. You can use the response() helper function to return a JSON response containing a given array or object:


return response()->json([
    'name' => 'John',
    'age' => 25
]);

The response() helper also allows you to specify the status code of your response. You can do this by passing in a second parameter to the json() method:


return response()->json([
    'name' => 'John',
    'age' => 25
], 200);

The status code parameter is optional, and if left out, your response will be sent with a 200 (OK) status code. You can also use the status() method to set the status code of your response:


return response()
    ->json([
        'name' => 'John',
        'age' => 25
    ])
    ->status(201);

You can also set custom headers for your response using the header() method:


return response()
    ->json([
        'name' => 'John',
        'age' => 25
    ])
    ->header('X-Custom-Header', 'MyValue');

The response() helper can also be used to return a view as a JSON response. This is useful for building single-page applications (SPAs) that consume a JSON API. To do this, you can use the view() method:


return response()->view('myview', [
    'name' => 'John',
    'age' => 25
]);

The view() method will render the specified view and return it as a JSON response. You can also set the status code and custom headers for the response in the same way as with the json() method.

Answers (0)