php - 在 Laravel 5 中间件中操作 JSON

标签 php json laravel laravel-5

我有一个发送到 Laravel 5 应用程序的 Ajax 请求。 但是在将 JSON 发送到 Controller 之前,我需要重新格式化/更改/... 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); 
    }
}

最佳答案

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

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

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

    }

}

在你的 Controller 上获取 json,而不是内容,否则你将得到没有我们过滤器的原始 json:

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

关于php - 在 Laravel 5 中间件中操作 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29797999/

相关文章:

php - mysql JSON_EXTRACT - 不返回任何结果

php - Laravel 5.5 - 排队事件监听器的 Horizo​​n 自定义作业标签

javascript - 仅显示基于 Angular 选择的事件

php - 将 MySQL UTC 日期时间转换为 UNIX 时间戳

php - 如何防止两个用户同时编辑相同的内容

php - 动态准备语句——这会打开安全漏洞吗?

php - Swift 2.0 - 将 JSON 值从 swift 存储到 php 变量并使用 php echo 显示

laravel - 下拉列表的基表

laravel - 如何从 Laravel 中的 .env 文件访问存储文件

javascript - 将 JS 处理的值附加到要以表单发送的文本区域