Search code examples
laravelmethodscontrollerexternallaravel-5

Call a method from one controller inside another


Is it possible to call a method from one controller inside another controller in Laravel 5 (regardless the http method used to access each method)?


Solution

  • This is how I have done it. Use the use keyword to make the OtherController available. Then you can call a method from that class on instantiation.

    <?php namespace App\Http\Controllers;
    
    use App\Http\Controllers\OtherController;
    
    class MyController extends Controller {
    
        public function __construct()
        {
            //Calling a method that is from the OtherController
            $result = (new OtherController)->method();
        }
    }
    

    Also check out the concept of a Command in Laravel. It might give you more flexibility than the method above.