Laravel Routing::检查参数值并重定向



我有一个GET类型的路由与一些参数。例如

Route::get('/my-route/{id}',array('uses'=>'myController@myAction'));

我想检查参数id的值,如果这个id=1,则重定向到另一条路由,否则继续。我所做的是这样的

Route::get('/my-route/{id}',function($id){
    if($id==1){
        return Redirect::to(URL::route('my-another-route'));
    }
    else{
        //What should I do here so my route works as before.
   }
});

在其他部分,我希望我的路由myController@myAction和参数。

谢谢

您可以这样做:

Route::get('/my-route/{id}',function($id){
    if($id==1){
        return Redirect::to(URL::route('my-another-route'));
    }
    else{
        return app()->call(myController::class, ['id' => $id], 'myAction');
   }
});

让它工作并路由到控制器的最简单方法是将Route恢复到原来的方式然后将if语句置于控制器条件的顶部:

public function myAction() {
    if ($id == 1) {
        return Redirect::to(URL::route('my-another-route'));
    }

放到控制器方法的顶部。

同样,如果你的路由上只使用uses => 'Controller@method',你可以这样做:

Route::get('/my-route/{id}','myController@myAction');

希望这对你有帮助!

最新更新