Laravel: Return JSON Response

To return a JSON response in Laravel, use the json() method on the response class, passing the JSON data as an associative array in the parenthesis of the method.

 

Here is an example of returning a JSON response from a function in Laravel:

 

return response()->json([
  'ajax_response' => false,
  'output' => 'Please try again.'
]);
{"ajax_response":false,"output":"Please try again."}

 

Conclusion

The Laravel json() method will automatically set the Content-Type header to application/json, and convert the given array to JSON using the json_encode() PHP function.