在 Laravel 中将当前路由与允许路由的数组进行比较

3

我不确定最好的方法是什么,所以将当前内容与一个数组进行比较只是我目前想到的。

我希望有一组路由执行一个过滤器,然后根据路由从该过滤器得到不同的结果。大致如下:

if(in_array($currentRoute, $allowedRoutes){
    do action1
}
else{
    do action2
}

就URI而言,我有许多不同的可能性。

Route::get('/content','ContentController@index')
Route::post('/dynamic/{dynamic}','DynamicController@store')
Route::delete('dynamic/{dynamic}/content/{content}','ContentController@destroy')

以上所有内容都可能有查询字符串,并且都具有多种HTTP方法。如何最好地处理这个问题呢?

1个回答

5
您可以为每个路由分配别名,以便您可以在查询字符串的情况下识别当前路由名称。例如:
Route::get('/content', array('uses'=>'ContentController@index', 'as'=>'content'))
Route::post('/dynamic/{dynamic}', array('uses'=>'DynamicController@store', 'as'=>'dynamic.show'))
Route::delete('dynamic/{dynamic}/content/{content}', array('uses'=>'ContentController@destroy', 'as'=>'dynamic.destroy'))

现在,在筛选器中,你可以做以下几件事:

$allowedRoutes = array('content');
$currentRoute = Route::currentRouteName();

if (in_array($currentRoute, $allowedRoutes)) {
    // do action1
} else {
    // do action2
}

请注意,此筛选器需要是一个“后置”筛选器,而不是一个“前置”筛选器。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接