Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulate JSON in Laravel 5 Middleware

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

Is there a way to manipulate the request body (JSON) in the 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); 
    }
}
like image 579
Pumper Avatar asked Apr 22 '15 12:04

Pumper


1 Answers

Yes it's possible you have two types of middlewares, the ones that run before the request and the ones that run after the request, you can find more info about it here.

To create a a middleware responsible for that you can generate one with this command:

php artisan make:middleware ProcessJsonMiddleware

Then register it with a friendly name on your kernel

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

This middleware is just an example, it removes the last element of the array and replaces it on the request:

<?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's 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);

    }

}

On your controller fetch the json, not the content, or you will get the raw json without our filter:

public function index(Request $request)
{
    //var_dump and die our filtered json
    dd($request->json()->all());
}
like image 183
Fabio Antunes Avatar answered Sep 25 '22 23:09

Fabio Antunes