简体   繁体   中英

Laravel check if route is api or web

How can I check wether the middleware is web or auth. Following Returns all routes, but I want to divide between api and web.

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

returns this:

Route {#109 ▼
  +uri: "oauth/authorize"
  +methods: array:2 [▶]
  +action: array:6 [▼
    "middleware" => array:2 [▼
      0 => "web"
      1 => "auth"
    ]
    "uses" => "\Laravel\Passport\Http\Controllers\AuthorizationController@authorize"
    "controller" => "\Laravel\Passport\Http\Controllers\AuthorizationController@authorize"
    "namespace" => "\Laravel\Passport\Http\Controllers"
    "prefix" => "oauth"
    "where" => []
  ]
  +controller: null
  +defaults: []
  +wheres: []
  +parameters: null
  +parameterNames: null
  +computedMiddleware: null
  +compiled: CompiledRoute {#203 ▶}
  #router: Router {#21 ▶}
  #container: Application {#3 ▶}
}

Simply do this:

1 . Get all routes and return them into your view:

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

2 . Run through a foreach check wether the prefix is correct and display them:

            @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

You can use this snippet if your API accept JSON. Note it won't work for other than JSON like XML, YAML, plain text, html etc.,

$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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM