🎓 A1Learner
🔍
0 of 50 lessons completed

Laravel JSON Responses

A JSON response is a response that sends data in JSON format. APIs use JSON responses to share data with other programs.

Send one item

An array with named keys becomes a JSON object.

return response()->json(['name' => 'Ada', 'age' => 36]);

Send a created status

The second value sets the status code.

return response()->json(['id' => 1, 'name' => 'Ada'], 201);

Send a list

An array without keys becomes a JSON list.

return response()->json(['Ada', 'Ben']);

Example

Route::get('/l23/user', function () {
    return response()->json(['name' => 'Ada', 'age' => 36]);
});

Key points

  • JSON: a text format for data, built from objects and lists.
  • Use response()->json() to turn a PHP array into a JSON response.
  • Use a second value to set the status, such as 201 for a created item.
  • Use a plain array for a list of values.

In this example, the route handles /l23/user. It passes an array to response()->json(). Laravel turns the array into a JSON object. A JSON response is a response that sends data in JSON format.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does response()->json(['name' => 'Ada']) send?