Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mu92's avatar
Level 1

how to use same controller function with rest api and http request

i have controller

class AbcController extends Controller { public function index() { $abcs= Abc::paginate(2);

if([request come from rest api] ) {
    return Response::json($tables);
} else {
        return view('index',[
            'abcs' => $abcs
        ]);
}

}

}

routes:

api.php

Route::get('abcs', [ 'uses' => 'AbcController @index' ]);

alos web.php

Route::get('abcs', [ 'uses' => 'AbcController @index' ]);

how i can check request comes from web or api?

0 likes
2 replies
RiccardoGaleazzi's avatar
Level 8

I guess you should not care of this. Laravel does it for you. Anyway APIs are just JSON request so you can check it in your controller with:

public function index(Request $request){
    if($request->wantsJson()){
        // I'm from API
    }else{
        // I'm from HTTP
    }
}

But as I said, do not do this. APIs may need versioning so it's better having a different controller: /v1.0.5/ApiController.php. Now you need to avoid repeating your logic and you can use Repository Pattern to accomplish this.

1 like

Please or to participate in this conversation.