How to Return JSON Response in Laravel?

By Hardik Savani April 16, 2024 Category : Laravel

Hi Friends,

This simple article demonstrates of how to return json response in laravel. If you have a question about laravel return json from controller then I will give a simple example with a solution. This article goes in detailed on return response()->json laravel. This example will help you laravel return json response with status code.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

In this example, i will give you simple three examples of how to return json response in laravel controller. we will use response()->json() function to return response in laravel.

So, let's see the simple examples:

Example 1:

app/Http/Controllers/UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

$user = User::first();

return response()->json(['success' => true]);

}

}

Output:

{

"success": true

}

Example 2:

app/Http/Controllers/UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

$user = User::first();

return response()->json(['success' => true], 201);

}

}

Output:

{

"success": true

}

Example 3:

app/Http/Controllers/UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

$user = User::get();

return $user;

}

}

Output:

[

{

"id": 1,

"name": "Hardik Savani",

"email": "antonetta69@example.net",

"email_verified_at": "2023-02-20T03:48:46.000000Z",

"created_at": "2023-04-28T03:48:46.000000Z",

"updated_at": "2023-01-20T03:48:46.000000Z",

"google_id": null,

"birthdate": null

},

{

"id": 2,

"name": "Brain Lebsack",

"email": "joana38@example.com",

"email_verified_at": "2023-02-20T03:48:46.000000Z",

"created_at": "2023-02-20T03:48:46.000000Z",

"updated_at": "2023-02-20T03:48:46.000000Z",

"google_id": null,

"birthdate": null

}

]

I hope it can help you...

Tags :
Shares