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

CookieMonster's avatar

Using same controller for web route and api route?

I am working on building API and so far i've familiar with the web route and I was wondering can you share the same controller for both web and api.

Say we created a post route in both web.php and api.php:

Route::post('/posts' , 'PostController@store')

And in the controller:

public function store(Request $request){
	$request->validate([
		'title' => 'required',
		'body' => 'required'
	]);

	Post::create([
		'title' => $request->title,
		'body' => $request->body
	]);
}

Since the logic for registering an api is similar to the web logic, do I need to create a separate PostApiController to handle the api request?

0 likes
7 replies
andyabihaidar's avatar

Technically it would work fine. However, from a best practice perspective, I prefer splitting my Api controllers into an Api folder in Controllers and having everything API related there.

Move your request validation to a form request ( https://laravel.com/docs/8.x/validation#form-request-validation ), that way you don't have to write it twice, and potentially you can also write a Post service class to handle creating a post that way you also only have the code in one place.

martinbean's avatar

@nickywan123 You can, but you shouldn’t.

Web and API are two different “layers” of your application. You’ll be doing things differently in your API than you will on the web. Your API will probably be returning single resource types and as JSON; your web controllers will be returning views with possibly more than just posts (i.e. other data needed for the view).

Create separate controllers, and move any duplicated code to a single location, be that a model, service class, etc.

1 like
CookieMonster's avatar

So for API, model should be stay as a single entity but for controllers, it should have a separate layer for API alone, correct(since API don't return views)?

What do you mean by duplicated code?

furqanDev's avatar

@CookieMonster API doesn't return views but data only. Web Routes return view along with the data. So you should keep the API routes in a separate file. You can even make versions of the APIs. For example your first version api was accessed by https://www.yoursite.com/api/v1/your-route. After that you made some changes and added new features then you can replace v1 with the version v2 or v3 or any version you like.

You can use web.php for api as well but you shouldn't. Even if you have 1 API route then you should go for the api.php file. and same goes for the controller as well. Simple web controller commonly has 7 methods and API Controller has 5 methods.

Please or to participate in this conversation.