I am building a Laravel Project where I have to build web and APIs for App. What is the best way to get ride of repetetive methods which are doing same thing but one is for Website and another is API.
e.g. I have to list jobs, in a particular category, on a website page and also have to build an API to list the available jobs in a category.
How can I make a single method for both web and API controllers.
For relatively simple applications; you can use content negotiation to determine how your application should respond, e.g.
public function index(Request $request)
{
$jobs = Job::where('category_id', $request->get('category'))->paginate();
if ($request->wantsJson()) {
return JobResource::collection($jobs);
}
return view('jobs.index', compact('jobs'));
}
The Eloquent query above is naive, but you should get the idea. The JobResourceAPI Resource class takes care of formatting the Response payload, which will keep your Controller action clean. I would define Routes in both web.php and api.php so the API endpoints can be stateless.
I define web and api endpoints separately because they serve different use cases. Controller methods should be simple anyway: they should handle top-level control flow and delegate heavy lifting to other methods or services, which can be reused. Validation can be reused through form request classes.
Truly reusable components, such as middleware, are a different matter. There, content negotiation is a must.
How can I make a single method for both web and API controllers.
@technosml Why? These are two separate entry points.
Create two controllers. You’re just trying to DRY things unnecessarily.
By all means, extract and consolidate the actual logic of these controllers, but I’d still have two separate routes and controllers, since you’re probably going to return JSON or something from your API controller, and more decorated HMTL views (with potentially other data sent to the view as well) from your web controller.