I have an RESTful API with controllers that should return a JSON response when is being hit by my android application and a \"view\" when it\'s being hit by a web browser. I\'m
Note::This is for future viewers
The approach I found convenient is to using a prefix api
for api calls. In the route file use
Route::group('prefix'=>'api',function(){
//handle requests by assigning controller methods here for example
Route::get('posts', 'Api\Post\PostController@index');
}
In the above approach, I separate controllers for api call and web users. But if you want to use the same controller then laravel Request
has a convenient way. You can identify the prefix within your controller.
public function index(Request $request)
{
if( $request->is('api/*')){
//write your logic for api call
$user = $this->getApiUser();
}else{
//write your logic for web call
$user = $this->getWebUser();
}
}
The is method allows you to verify that the incoming request URI matches a given pattern. You may use the * character as a wildcard when utilizing this method.