2013-08-15 20 views
22

È possibile accedere ai parametri del percorso all'interno di un filtro?Passare argomenti a un filtro - Laravel 4

ad es. Voglio accedere al parametro $ agencyId:

Route::group(array('prefix' => 'agency'), function() 
{ 

    # Agency Dashboard 
    Route::get('{agencyId}', array('as' => 'agency', 'uses' => 'Controllers\Agency\[email protected]')); 

}); 

Voglio accedere a questo parametro $ agencyId nel mio filtro:

Route::filter('agency-auth', function() 
{ 
    // Check if the user is logged in 
    if (! Sentry::check()) 
    { 
     // Store the current uri in the session 
     Session::put('loginRedirect', Request::url()); 

     // Redirect to the login page 
     return Redirect::route('signin'); 
    } 

    // this clearly does not work..? how do i do this? 
    $agencyId = Input::get('agencyId'); 

    $agency = Sentry::getGroupProvider()->findById($agencyId); 

    // Check if the user has access to the admin page 
    if (! Sentry::getUser()->inGroup($agency)) 
    { 
     // Show the insufficient permissions page 
     return App::abort(403); 
    } 
}); 

Solo per riferimento Io chiamo questo filtro nel mio controller in quanto tale:

+2

si può usare questo '$ agencyId = Request :: segment (2) 'per ottenere' agencyId' nel filtro –

risposta

28

Input::get può recuperare solo argomenti GET o POST (e così via).

Per ottenere parametri del percorso, si deve afferrare Route oggetto nel filtro, in questo modo:

Route::filter('agency-auth', function($route) { ... }); 

e ottenere parametri (nel filtro):

$route->getParameter('agencyId'); 

(solo per divertimento) Nel tuo percorso

Route::get('{agencyId}', array('as' => 'agency', 'uses' => 'Controllers\Agency\[email protected]')); 

è possibile utilizzare nell'array dei parametri 'before' => 'YOUR_FILTER' anziché specificarlo nel costruttore.

14

Il nome del metodo è stato modificato in Laravel 4.1 e parameter. Per esempio, in un controller RESTful:

$this->beforeFilter(function($route, $request) { 
    $userId = $route->parameter('users'); 
}); 

Un'altra opzione è quella di recuperare il parametro attraverso il Route facciata, che è utile quando si è al di fuori di un percorso:

$id = Route::input('id');