Handle API Routes and Web Routes on the same Methods?
Suppose I have a controller with your typical CRUDdy resource routes (index, show, store, etc.), and associated routes in the api.php routes file. Now suppose I want to build a back-end interface to manage this API. The index route is already just returning Model::all(). That obviously is far from sufficient for building a real view to manage it. How can I use the same Controller method to either return a view with additional logic, or a JSON object, depending on whether the request came from api or web?
PS: Checking isAjax is not sufficient, as you can access APIs from PHP and other back-end languages that would fail the isAjax check.
why would you want to use the same Controller::method ?
one is for API, the other for Web. they do different things.
even if they are sharing some code, separate them. Then pull the shared code out to a repos or service provider, just a simple class, or what not. (I go with simple class)
Ideally the end result (2 slim controllers), where one spits out json, and another a view.
You could use if( request()->wantsJson() ) { // do JSON-y stuff }
but you should ideally do this is in two separate controllers, one for APIs and one for web. There are additional middleware that gets applied to API vs web, and vice versa. CSRF protection is one of them that is available by default on web, but not on API. Request throttling is another one for API, that doesn't apply to web.