Laravel return JSON from controller with example
Laravel return JSON from controller with example

Laravel return JSON response from controller with example

Laravel return JSON from controller with example

In Laravel, both JsonResponse and response()->json() are used to return JSON responses from a controller. They are essentially two different ways to achieve the same result.

In Laravel, you can return JSON responses from a controller using the json method or by returning an array or an instance of the JsonResponse class. Here are a few examples:

Example 1: Using the json method:

Route::get('/json-response', function ()  {
    $data = [
        'status' => 'success',
        'message' => 'Data retrieved successfully',
        'data' => User::take(5)->pluck('email'),
    ];
    
    return response()->json($data);
});

Same result can be achieved by returning the array directly:

public function exampleArray()
{
    $data = [
        'status' => 'success',
        'message' => 'Data retrieved successfully',
        'data' => ['key' => 'value'],
    ];

    return $data;
}

 

Response of the example will be like:

{
  "status": "success",
  "message": "Data retrieved successfully",
  "data": [
    "vimaqybyf@mailinator.com",
    "jytihy@mailinator.com",
    "sacilalyk@mailinator.com",
    "fewyzifi@mailinator.com",
    "sdgfjshdfdgdf@mail.com"
  ]
}

 

 

Example 2: Using JsonResponse Class

In Laravel, JsonResponse is a class provided by the framework that allows you to create JSON-formatted HTTP responses. This class extends Laravel’s Symfony\Component\HttpFoundation\JsonResponse class, providing additional features and integration with Laravel’s response system. Like:

  1. HTTP Status Code Setting: We can set the HTTP status code for the response using the setStatusCode method. This method allows us to send responses with appropriate status codes based on the result of your operation. e.g: $response->setStatusCode(200);
  2. Header Manipulation: We can add, modify, or remove headers using methods like header, withHeaders, headerBag, etc. This gives us control over HTTP headers sent with the response.
  3. JSON Options: JsonResponse allows us to set various options related to JSON encoding and decoding using the setEncodingOptions method. For example, we can specify JSON options like JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, etc.
  4. Response Transformation: We can transform the response data before it’s encoded into JSON using the setData method. This allows you to manipulate the data just before it’s sent, which can be useful for formatting or processing.
  5. Callback Support: JsonResponse supports JSONP (JSON with padding) responses. We can set the callback function name using the setCallback method, allowing cross-domain AJAX requests in certain scenarios.
  6. Response Helpers: Laravel’s JsonResponse class provides several helper methods like setContent, setJson, setData, etc., which allow you to conveniently manipulate the response content.

These additional features give us more control and flexibility when working with JSON responses in Laravel. Depending on your requirements, you can leverage these features to tailor your responses to suit your application’s needs.

Don not forgot to use: use Illuminate\Http\JsonResponse; in top of the class.

Route::get('/json-response', function ()  {
    $data = [
        'status' => 'success',
        'message' => 'Data retrieved successfully',
        'data' => User::orderBy('id', 'desc')->take(5)->pluck('email'),
    ];

    return new JsonResponse($data);

    // return response()->json($data);
});

Response of the example will be like:

{
  "status": "success",
  "message": "Data retrieved successfully",
  "data": [
    "vimaqybyf@mailinator.com",
    "jytihy@mailinator.com",
    "sacilalyk@mailinator.com",
    "fewyzifi@mailinator.com",
    "sdgfjshdfdgdf@mail.com"
  ]
}

 

Both approaches will send a JSON response with the specified data. The response()->json() method is a convenient helper method provided by Laravel, which internally creates an instance of the JsonResponse class.

Using response()->json() is more concise and is commonly used in Laravel applications. It is a shorthand way of creating a JSON response. The JsonResponse class, on the other hand, allows for more customization and is useful if you need to set additional headers or options on the response.

In summary, for most cases, using response()->json() is the preferred and concise way of returning JSON responses in Laravel.

Any of these approaches will send a JSON response with the specified data. Choose the one that best fits your coding style and requirements. Laravel will automatically set the appropriate headers for a JSON response.

 

Check Out More Resources:

Articles:
Website: https://laravelplug.com/
YouTube Channel: https://www.youtube.com/channel/UCnTxncHQcBSNs4RCuhWgF-A?sub_confirmation=1
WordPress Playlist: https://www.youtube.com/watch?v=8VvXzFAFwQU&list=PLVoVZqAh8dTLHZ51egvEU7dsOrRCSIMWx
Tools Playlist: https://www.youtube.com/watch?v=gTQoUn3BQkM&list=PLVoVZqAh8dTK-DWHBGWOEEvzvPQrgFne-

WordPress Tutorials: https://laravelplug.com/category/wordpress/
Laravel Tutorials: https://laravelplug.com/category/laravel/
PHP Tutorials: https://laravelplug.com/category/php/
SQL Tutorials: https://laravelplug.com/category/sql/
Various Tips: https://laravelplug.com/category/tips/
Useful Tools: https://laravelplug.com/category/tools/

Socials:

Twitter: https://twitter.com/LaravelPlug
Pinterest: https://www.pinterest.com/LaravelPlugCom/
Facebook: https://www.facebook.com/groups/1020759861842360
Mail: info@laravelplug.com

#Laravel #sql #mysql

 

That’s All. Feel free to knock me. Thanks.

Editorial Staff

A Learner and trying to share what I learned!