Returning a JSON response from a Laravel controller with a specific status code, message, data and array is a fundamental and frequently occur task when developing an API or working with AJAX requests.
To return a JSON response in Laravel, you can use the response() function and include the JSON data in the response using the json() method. In this tutorial, you will learn how to return a JSON response in Laravel from the controller with a status code, message(success, error, etc), and data, array.
Laravel 10|9|8 Return JSON Response Tutorial
Steps to return a JSON response in Laravel from controller with status code, messages(success, error,etc), and data, array:
- Step 1: Create a Controller
- Step 2: Define Methods in Controller
- Step 3: Create the JSON Response
- Step 4: Create a Route
- Step 5: Test Your API
Step 1: Create a Controller
If you don’t already have a controller, you can create one using the artisan
command-line tool. Run the following command to create a new controller:
php artisan make:controller ApiController
This command will create a new controller file named ApiController.php
in the app/Http/Controllers
directory.
Step 2: Define Methods in Controller
Once you have created ApiController.php
file into your laravel project. Now, you need to define a method that will handle the JSON response. For this example, let’s create a method called getResponse
:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ApiController extends Controller
{
public function getResponse()
{
// Your logic to generate JSON data
}
}
Step 3: Create the JSON Response
Next, in the getResponse
method, you can create an array of data that you want to return as JSON. You can use the json
method provided by Laravel’s Response
class to build the JSON response. Here’s an example:
public function getResponse()
{
$data = [
'message' => 'Hello, JSON World!',
'status' => 'success',
];
return response()->json($data, 200);
}
Step 4: Create a Route
Next, you need to define a route that maps to the getResponse
method in your web.php
or api.php
file (depending on whether you’re building a web or API route). Here’s an example:
use App\Http\Controllers\ApiController;
Route::get('/api/response', [ApiController::class, 'getResponse']);
This code maps the getResponse
method to the URL /api/response
. Adjust the route and URL according to your project’s requirements.
If you are unfamiliar with the process of building a RESTful API in Laravel, you can find guidance in this instructional guide.
Step 5: Test Your API
You can now test your JSON response by visiting the URL you’ve defined in your route (e.g., http://your-app-url/api/response
). You should see a JSON response like this:
{
"message": "Hello, JSON World!",
"status": "success"
}
Conclusion
Congratulations! You’ve successfully created a JSON response in Laravel and returned it from the controller with a specific status code, message, and array data.
Recommended Tutorials