How to Call a Controller Method from Another Controller in Laravel?

I’m working on a delivery module for a third-party Laravel point-of-sale (POS) application. In this module, I need to add some functionality to the existing store method of SaleController. However, I want to achieve this without directly modifying the original application’s codebase. I want to call the store method in my module and then add the additional functionality required for the delivery feature.

Original SaleController

class SaleController extends Controller
{
    public function store()
    {
        // Original store method logic
    }
}

Module DeliveryController

class DeliveryController extends Controller
{
    public function addDelivery(Request $request)
    {
        // Call the Store method directly here
        new SaleController()->store();

        // Add Delivery Functionality
    }
}

This is what I am trying to do. Can anyone help me solve this?

You have 2 options.

  1. You can directly call the store method from SaleController using Laravel’s service container.
class DeliveryController extends Controller
{
    public function addDelivery(Request $request)
    {
        // Call the Store method directly here
        app('App\Http\Controllers\SaleController')->store($request);

        // Add Delivery Functionality
    }
}
  1. You can use the SaleController service class. You can inject an instance of SaleController into DeliveryController and then call its store method.
use App\Http\Controllers\SaleController;

class DeliveryController extends Controller
{
    protected $saleController;

    public function __construct(SaleController $saleController)
    {
        $this->saleController = $saleController;
    }

    public function addDelivery(Request $request) 
    {
        // Call the store method from SaleController
        $this->saleController->store($request);

        // Add additional functionality for delivery
    }
}