Laravel Route::get using where conditions

懵懂的女人 提交于 2019-12-12 06:05:49

问题


I'm working on Laravel 5.1 and I have the following code:

//Routes.php
Route::get('/listagem/{campo}','ControllerParque@listar');

//ControllerParque.php
    public function listar($campo) {       
        $listagem = DB::SELECT("SELECT COUNT(x.".$campo.") AS nreg, x.* FROM (SELECT * FROM computadores ORDER BY id DESC) AS x GROUP BY ".$campo." ORDER BY ".$campo." ASC");  
        $dados = array('listagem' => $listagem, 'campo' => $campo);
        return view("ViewListagem")->with($dados);           
    }

I would like to restrict anything different of 'listagem/usuario' or 'listagem/tag'. I mean, if an user types in your navigator (URL bar) 'listagem/crap', it will be denied, because it's not 'listagem/usuario' or 'listagem/tag'.

I've tried 'where' clause':

Routes.php
    Route::get('/listagem/{campo}','ControllerParque@listar')
->where('campo', 'usuario');

But this way I'm restricting just the one condition, this case 'listagem/usuario'.

Any idea?


回答1:


You can use a regular expression in the "where" clause. usario|tag would match only usario or tag http://laravel.com/docs/5.0/routing#route-parameters

Route::get('/listagem/{campo}','ControllerParque@listar')
    ->where('campo', 'usuario|tag');



回答2:


I'm not sure if it can be done via the where. Instead, you can check for it within the controller function.

public function listar($campo) {  
     if(!in_array($campo,['usuario','tag'])) {
          // throw an error, return to previous page
          return Redirect::back()->withErrors('error message here');
     }
     // Continue on with your function
}


来源:https://stackoverflow.com/questions/34404060/laravel-routeget-using-where-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!