在Laravel 5 Middleware中操作JSON

Pum*_*per 5 php json laravel laravel-5

我有一个Ajax请求,发送到Laravel 5应用程序.但是在将JSON发送给控制器之前,我需要重新格式化/更改/ ... JSON.

有没有办法在中间件中操纵请求体(JSON)?

<?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); 
    }
}
Run Code Online (Sandbox Code Playgroud)

Fab*_*nes 5

是的,您可能有两种类型的中间件,即在请求之前运行的中间件和在请求之后运行的中间件,您可以在此处找到有关它的更多信息.

要创建一个负责的中间件,您可以使用以下命令生成一个:

php artisan make:middleware ProcessJsonMiddleware
Run Code Online (Sandbox Code Playgroud)

然后在内核上使用友好名称注册它

protected $routeMiddleware = [
        'auth' => 'App\Http\Middleware\Authenticate',
        'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
        'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
        'process.json' => 'App\Http\Middleware\ProcessJsonMiddleware',
    ];
Run Code Online (Sandbox Code Playgroud)

这个中间件只是一个例子,它删除了数组的最后一个元素并在请求中替换它:

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

    }

}
Run Code Online (Sandbox Code Playgroud)

在您的控制器上获取json,而不是内容,或者您​​将获得没有我们的过滤器的原始json:

public function index(Request $request)
{
    //var_dump and die our filtered json
    dd($request->json()->all());
}
Run Code Online (Sandbox Code Playgroud)