2015-06-13 46 views
2

我想將模型參數傳遞給中間件。根據這一link (laravel 5 middleware parameters),我可以只包括在handle()功能,像這樣一個額外的參數:Laravel 5:將模型參數傳遞給中間件

public function handle($request, Closure $next, $model) 
{ 
    //perform actions 
} 

你如何將它傳遞在控制器的構造函數?這是行不通的:

public function __construct(){ 
    $model = new Model(); 
    $this->middleware('myCustomMW', $model); 
} 

**注:**,我可以通過不同的模型(前ModelX,ModelY,ModelZ)

回答

2

首先確保你是很重要的使用Laravel 5.1。中間件參數在以前的版本中不可用。

現在我不相信你可以將一個實例化對象作爲參數傳遞給你的中間件,但是如果你確實需要這個參數的話,你可以傳遞一個模型的類名,也就是說,如果你需要一個特定的實例,就可以傳遞主鍵。

在你的中間件:

public function handle($request, Closure $next, $model, $id) 
{ 
    // Instantiate the model off of IoC and find a specific one by id 
    $model = app($model)->find($id); 
    // Do whatever you need with your model 

    return $next($request); 
} 

在你的控制器:

use App\User; 

public function __construct() 
{ 
    $id = 1; 
    // Use middleware and pass a model's class name and an id 
    $this->middleware('myCustomMW:'.User::class.",$id"); 
} 

通過這種方法,你可以通過你想你的中間件任何車型。

0

解決該問題的更雄辯方式是在中間件創建構造方法,注入所述模型(或多個)作爲依賴關係,將它們傳遞到類變量,然後利用在手柄方法的類的變量。

有關驗證我的響應的權限,請參閱Laravel 5.1安裝中的app/Http/Middleware/Authenticate.php。

中間件MyMiddleware,模型$基於myModel,類爲MyModel的,請執行以下操作:

use App\MyModel; 

class MyMiddleware 
{ 
    protected $myModel; 

    public function __construct(MyModel $myModel) 
    { 
     $this->myModel = $myModel; 
    } 

    public function handle($request, Closure $next) 
    { 
     $this->myModel->insert_model_method_here() 
     // and write your code to manipulate the model methods 

     return $next($request); 
    } 
} 
相關問題