How to Return JSON from Controller in Laravel: Simple Guide
In Laravel, you can return JSON from a controller by returning an array or collection directly, which Laravel automatically converts to JSON, or by using the
response()->json() helper method for more control. Both methods send a JSON response to the client with the correct headers.Syntax
There are two common ways to return JSON from a Laravel controller:
- Return an array or collection: Laravel converts it automatically to JSON.
- Use
response()->json()helper: This method allows setting status codes and headers explicitly.
Example syntax:
return [ 'key' => 'value' ];
// or
return response()->json([ 'key' => 'value' ], 200);php
return ['message' => 'Hello, world!']; // or return response()->json(['message' => 'Hello, world!'], 200);
Example
This example shows a Laravel controller method returning JSON data using both direct return and the response()->json() helper. It demonstrates how Laravel sends a JSON response with the correct headers.
php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class ApiController extends Controller { public function getData() { // Returning array directly // Laravel converts this to JSON automatically // return ['status' => 'success', 'data' => ['name' => 'Alice', 'age' => 30]]; // Using response()->json() for more control return response()->json([ 'status' => 'success', 'data' => [ 'name' => 'Alice', 'age' => 30 ] ], 200); } }
Output
{"status":"success","data":{"name":"Alice","age":30}}
Common Pitfalls
Common mistakes when returning JSON in Laravel include:
- Returning a string or non-array/non-collection without using
response()->json(), which may not set the correct JSON headers. - Forgetting to set the correct HTTP status code when needed.
- Returning views or HTML instead of JSON in API routes.
Example of a wrong and right way:
php
<?php // Wrong: returns plain string without JSON headers return 'Hello World'; // Right: returns JSON with proper headers return response()->json(['message' => 'Hello World']);
Quick Reference
Summary tips for returning JSON in Laravel:
- Return arrays or collections directly for simple JSON responses.
- Use
response()->json()to set status codes and headers explicitly. - Always ensure your API routes expect JSON responses.
- Use HTTP status codes to indicate success or errors.
Key Takeaways
Return arrays or collections directly from controller methods to get JSON responses automatically.
Use response()->json() helper to customize JSON response status and headers.
Avoid returning plain strings without JSON headers for API responses.
Set appropriate HTTP status codes when returning JSON for better API communication.
Ensure your routes and clients expect JSON to avoid confusion.