Laravel检查路由是api还是web

时间:2017-07-13 10:32:04

标签: php laravel routes laravel-5.4

我如何检查中间件是web还是auth。 以下返回所有路由,但我想在api和web之间划分。

<div class="uk-form-row">
      <label class="uk-form-label"><?php echo Yii::t("default","SMTP port")?></label>  
      <?php 
      echo CHtml::textField('smtp_port',
      Yii::app()->functions->getOptionAdmin('smtp_port'),
      array(
        'class'=>"uk-form-width-large"    
      ))
      ?> 
    </div>

    <div class="uk-form-row">
      <label class="uk-form-label"><?php echo Yii::t("default","Username")?></label>  
      <?php 
      echo CHtml::textField('smtp_username',
      Yii::app()->functions->getOptionAdmin('smtp_username'),
      array(
        'class'=>"uk-form-width-large"    
      ))
      ?> 
    </div>

    <div class="uk-form-row">
      <label class="uk-form-label"><?php echo Yii::t("default","Password")?></label>  
      <?php 
      echo CHtml::textField('smtp_password',
      Yii::app()->functions->getOptionAdmin('smtp_password'),
      array(
        'class'=>"uk-form-width-large"    
      ))
      ?> 
    </div>

    <p class="uk-text-danger uk-text-small"><?php echo t("Note: When using SMTP make sure the port number is open in your server")?>.<br/>
    <?php echo t("You can ask your hosting to open this for you")?>.
    </p>

    </li>

返回:

$routes = app()->routes->getRoutes();
foreach($routes as $routeKey => $routeValue)
{
    dd($routeValue);
}

3 个答案:

答案 0 :(得分:0)

只需这样做:

1。获取所有路线并将其返回到您的视图中:

public function index(Request $request)
{
    $routes = app()->routes->getRoutes();
    return view ('api.doc.index',compact('routes'));
}

2。通过foreach检查运行前缀是否正确并显示它们:

            @foreach ($routes as $routeKey => $routeValue)
                @if($routeValue->getPrefix() == 'api')
                <tr>
                    <td>{{$routeValue->uri}}</td>
                    <td>{{$routeValue->getName()}}</td>
                    <td>{{$routeValue->getPrefix()}}</td>
                    <td>{{$routeValue->getActionMethod()}}</td>
                </tr>
                @endif
            @endforeach

答案 1 :(得分:0)

如果您的API接受JSON,则可以使用此代码段。请注意,它不适用于JSON,例如XML,YAML,纯文本,html等。

$msg = config('constants.messages.MSG001');
if ($request->wantsJson()) { //Here we check if the request wants response in JSON

  $response = ['success' => FALSE, 'message' => $msg];
  return response($response);
} else { //If request don't wants JSON we redirect it to login page with message.

  Auth::logout();
  return redirect('/login')->with('error', $msg);
}

答案 2 :(得分:0)

我找到了两种判断请求是否来自 API 的方法:

你可以检查路由是否有“api”前缀(看起来更干净)

$is_api_request = $request->route()->getPrefix() === 'api';

或者检查它是否有“api”请求中间件

$is_api_request = in_array('api',$request->route()->getAction('middleware'));

在 Laravel 8 上测试