Spread the love

In this tutorial we will learn to modify the JSON and add new content to it. sometime we need to add some global data to every API, so in this article we will create a middleware and temper the sons response.

I assume you well know to Laravel middleware and if not then you can read this article custom Laravel middlware

Let’s begin with simple step by step process:

Step 1: Create a middleware

Create a middleware using simple artisan command

php artisan make:middleware JsonResponseMiddleware

Step 2: Add Middleware in routes in Laravel 8

Create routes and use the middleware

<?php

use Illuminate\Support\Facades\Route;
use \App\Http\Controllers\Api\PostController;
use App\Http\Middleware\JsonResponseMiddleware;
 
Route::middleware(JsonResponseMiddleware::class)->group(function(){
  Route::get("add-post",[PostController::class, 'create']);
});

Step 3: Implement the logic in middleware

We have created our custom middleware and defined in kernel, now it’s time e to implement the our core logic for check blacklisted user.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class JsonResponseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);  // after request completion get the controller response her
        
        if($response instanceof \Illuminate\Http\JsonResponse){

            $current_data = $response->getData();

            $current_data->user_status = ['add some data here'];

            $response->setData($current_data);
        }
        return $response;
        
    }
}

As you can see we have handled $response = $next($request); the response and checking here that if $response variable is instance of \Illuminate\Http\JsonResponse then we can add others keys to response data.

Step 4: Create Controller and test the implementation

Now, create a controller in api folder and check the implementation

<?php

namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class PostController extends Controller
{

     /**
     * Show the form to create a new blog post.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
       return response()->json(["status"=>true,"message"=>"success"]);
    }
}

Output:

Leave a Reply