Reputation: 315
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 ▶}
}
Upvotes: 2
Views: 10209
Reputation: 784
I found two ways of telling if the request comes from the API:
you can check if the route has an "api" prefix (seems cleaner)
$is_api_request = $request->route()->getPrefix() === 'api';
Or check if it has the "api" request middleware
$is_api_request = in_array('api',$request->route()->getAction('middleware'));
Tested on Laravel 8
Upvotes: 7
Reputation: 2506
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);
}
Upvotes: 1
Reputation: 4102
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
Upvotes: 0