Manipulate JSON in Laravel 5 Middleware

I have an Ajax request that is sent to a Laravel 5 application. But I need to reformat / change / ... JSON before sending it to the controller.

Is there a way to manipulate a request body (JSON) in middleware?

<?php namespace App\Http\Middleware;

use Closure;

class RequestManipulator {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->isJson())
        {
            $json = json_decode($request->getContent(), TRUE);
            //manipulate the json and set it again to the the request
            $manipulatedRequest = ....
            $request = $manipulatedRequest;
        }
        \Log::info($request);
        return $next($request); 
    }
}
+4
source share
1 answer

Yes, perhaps you have two types of intermediaries: those that run before the request and those that run after the request, you can find additional information about this.

To create the middleware responsible for this, you can generate it with this command:

php artisan make:middleware ProcessJsonMiddleware

protected $routeMiddleware = [
        'auth' => 'App\Http\Middleware\Authenticate',
        'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
        'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
        'process.json' => 'App\Http\Middleware\ProcessJsonMiddleware',
    ];

, :

<?php namespace App\Http\Middleware;

use Closure;
use Tokenizer;

class ProcessJsonMiddleware {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->isJson())
        {
            //fetch your json data, instead of doing the way you were doing
            $json_array = $request->json()->all();

            //we have an array now let remove the last element
            $our_last_element = array_pop($json_array);

            //now we replace our json data with our new json data without the last element
            $request->json()->replace($json_array);
        }

        return $next($request);

    }

}

json, , json :

public function index(Request $request)
{
    //var_dump and die our filtered json
    dd($request->json()->all());
}
+5

Source: https://habr.com/ru/post/1584019/


All Articles