Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinguish between a call from web route vs API route?

In my web.php file, I have a route that looks like this:

Route::get('/', 'HomeController@getFeed');

And in my api.php file, I have a route that looks like this:

Route::get('feeds', 'HomeController@getFeed');

Notice that they both call the same method, getFeed().

Is there a way to distinguish whether the call came from the web route vs the API route in the controller's method? I need to be able to return two different responses, one for the web route and one for the API route.

Here is the HomeController.php class:

class HomeController extends Controller
{
    public function getFeed() {
        $user = Auth::user();

        // How to check if call is from web route or API route?
        // Need to return two different responses for each scenario.
    }
}

Thanks.

like image 797
k6515612 Avatar asked Feb 05 '23 16:02

k6515612


1 Answers

All routes from api.php are automatically prefixed with 'api/' So you can use he below code to check

    if (Request::is('api*')) {
        echo "request from api route";
        exit();
    }else{
        echo "request from web";
        exit();
    }
like image 121
SHENE Avatar answered Feb 08 '23 14:02

SHENE