From my understanding, we put the majority of the logic in the model, returning results to both the API and WEB controllers that then handle how the data is then presented to their respective destinations.
@ady_gould Yeah, pretty much. If you can keep as much logic in models and services classes, then your controllers end up being “marshals” that take a HTTP request, call the relevant domain logic, and then present the results (whether that be in a Blade template or as a JSON/XML response or whatever).
So if you have an API endpoint to create a post, as well as the ability to create a post from the “web” front-end, then the respective controllers could call on the same service method to accomplish that:
namespace App\Http\Controllers;
class PostController extends Controller
{
protected $postService;
public function __construct(PostService $postService)
{
$this->postService = $postService;
}
public function store(StoreArticleRequest $request)
{
$post = $this->postService->create($request->validated());
return redirect('/posts')->with('success', 'Post was created.');
}
}
namespace App\Http\Controllers\Api;
class PostController extends Controller
{
protected $postService;
public function __construct(PostService $postService)
{
$this->postService = $postService;
}
public function store(StoreArticleRequest $request)
{
$post = $this->postService->create($request->validated());
return new JsonResponse($post, 201);
}
}
So both controllers call on the same class and method to create a post, but return different responses depending on if it’s the “web” controller or the API controller. This means that if you need to change how a post is created, you only need to do that in one place (the PostService class).
With this in mind, creating controllers with names such as ProductsApiController and ProductsController would allow the two to be separate but relatively easy to maintain.
I tend to namespace controllers. So above you’ll see I put the API controller in its own sub-namespace (App\Http\Controllers\Api) so that API controllers are separated from the “web” controllers. I’ll do the same for controllers for things like admin panels or whatnot. But this is just personally preference.