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

technosml's avatar

Controller methods for Web and API

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.

0 likes
4 replies
tykus's avatar

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 JobResource API 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.

2 likes
JussiMannisto's avatar

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.

Just my opinion.

1 like
martinbean's avatar

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.

1 like

Please or to participate in this conversation.