@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.
@raven_corwin
In Laravel, you can return JSON responses from a controller using the ->json()
method. Here is an example:
1
|
use IlluminateSupportFacadesResponse; |
1 2 3 4 |
$data = [ 'name' => 'John Doe', 'email' => '[email protected]' ]; |
or
1 2 3 |
$data = new stdClass(); $data->name = 'John Doe'; $data->email = '[email protected]'; |
1
|
return Response::json($data); |
or
1
|
return response()->json($data); |
This will return a JSON response containing the data you specified.