Laravel 一次只能访问两条路线中的一条

Laravel only one of two routes accessible at a time

如果我的 web.php 中有两条路线 A 和 B。我怎样才能像这样进行中间件检查:

if (something in my database have status == 0) {
    return $next($request); ROUTE A
} else {
    return $next($request); ROUTE B
}

我提到return $next($request);是因为这里有一个条件,我不希望这些路由同时可访问。因此,例如,如果我去 url/routeA 如果满足条件,则允许如果不显示路线 B。路线 B ​​也是如此。

逻辑就像这样,用户从列表中选择一个项目(在数据库中,列表表示如下:listid,name,status)如果状态为 0 显示路由 A 如果状态为 1 显示路线 B。如果我尝试访问 url/routeB?listID1 直接检查条件(对于 id1)并显示路线 A 或 B。

状态只有0或1。如果状态为 1,所有用户将直接访问 routeB,如果状态为 0,则第一个到达那里的用户将访问 routeA 并执行某些操作(将状态设置为 1)并重定向到 routeB。他之后的下一个用户将直接到达routeB

您可以使用路由名称并在任何地方使用它。

  //define route
  Route::get('/A', 'ControllerA@methodA')->name('A');
  Route::get('/B', 'ControllerB@methodB')->name('B');

In your controller simply use route name

   $routeName = ['A','B']; //route name
   If (something in my database have status == 0) {
     return Redirect::route($routeName[0]); //ROUTE A
   } else {
      return Redirect::route($routeName[1]); //ROUTE B
   }

Otherwise you can do something getting route group parameter

  Route::group(['prefix' => '/test/{id}'], function() {
   //you can't access parameter directly here 
    $id = explode('test/',url()->current())[1]; //get parameter with different way
    if($id == 1){
       exit('do something');
    }else{
        exit('do others');
    }
 });

如果需要,您可以从中间件进行重定向:

if (something in my database have status == 0) {
    return redirect()->route('route_a_name');
} else {
    return redirect()->route('route_b_name');
}

只需确保在 routes/web.php 中命名路线即可。

示例:

Route::get('/route_a', 'YourController@RouteA')->name('route_a_name');

编辑:

根据您提供的附加信息,您试图实现的中间件有点过头了。相反,您可以简单地使用单个路由并传入状态参数。有关路由参数的更多信息,请参阅 https://laravel.com/docs/5.6/routing#route-parameters

示例:

Route::get('/your_route/{status}', 'YourController@ControllerAction');

然后在你的控制器中,根据状态处理逻辑:

function ControllerAction(Request $request, $status) {
    if ($status == 0) {
        //Show view for A
    } else {
        //Show view for B
    }
}