2015-04-22 25 views
4

我有一個發送到Laravel 5應用程序的Ajax請求。 但我需要在將它發送給控制器之前重新格式化/更改/ ... JSON。在Laravel 5中間件中操作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); 
    } 
} 
+1

不同於論壇的網站,我們不使用「謝謝」,或者「任何幫助表示讚賞」,或[Stack Overflow]簽名(http://stackoverflow.com/)。見[「應該'嗨','謝謝''標語和祝福從帖子中刪除?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be -removed - 從 - 個)」。順便說一句,它是「提前致謝」,而不是「先進感謝」。 –

回答

5

是的,它可能有兩種類型的中間件的,該請求之前運行的那些與該請求後運行的,你可以找到關於它的here更多信息。

要創建負責人認爲AA中間件就可以生成一個與此命令:

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

    } 

} 

在您的控制器獲取JSON,而不是內容,或者你會得到的原始JSON沒有我們的過濾器:

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

您的工匠命令中有一個錯字:ProcessJsontMiddleware 不錯的答案;) – Luceos

+0

糟糕,修復它。謝謝 –

+0

我已經嘗試過使用自定義請求進行驗證,而不是「請求」,並且它在爲\ Illuminate \ Http \ Request工作時無效。任何想法爲什麼發生這種情況 –