skip to Main Content

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

I already have a controller file which is working for web route right now

LIke this url for the web route :

Route::post('product', [GuestuserController::class, 'product']);

Now i want to use same controller for API too because i don`t want to update the code for API again again if anything change in web code , i want the changes make in web automatically reflect the API too.

Could anyone suggest me a solution for this so i can move further.

2

Answers


  1. Although it’s possible to define the same controller in api.php and web.php, it’s not a good practice.

    You should rather, create a service class and move your business logic there.
    This way, you can call the service from any controller, API, or web

    Example

    <?php
    
    namespace AppServices;
    
    use AppModelsProduct;
    
    class ProductService
    {
        public static function create(string $name, string $description) : Product
        {
            // logic
    
            // other logics
    
            $product = Product::create([
                'name'        => $name,
                'description' => $description
            ]);
    
            // more logics, maybe send email :)
    
            return $product;
        }
    }
    

    Then in API controller or Web controller

    namespace AppHttpControllersAPI;
    
    use AppHttpControllersController;
    use AppHttpRequestsProductStoreRequest;
    use AppServicesProductService;
    
    class ProductController extends Controller
    {
        public function store(StoreRequest $request)
        {
            $validated = $request->validated();
            $product = ProductService::create(
               $validated['name'],
               $validated['description']
            );
            //Maybe return a JSON response
        }
    }
    
    Login or Signup to reply.
  2. It depends. But a clear demarcation would be advantageous. You never know. Example what you could do:

    web.php uses :
    class AController extends ParentController {}

    api.php uses:
    class Api/AController extends ParentController {}

    In the ParentController you add your common methods that use the web as well as the api route. This way you would be more flexible than with your variant and you don’t have any redudant code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search