Call a method from one controller inside another

前端 未结 2 1358
感动是毒
感动是毒 2021-01-12 04:46

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)?

相关标签:
2条回答
  • 2021-01-12 05:29

    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.

    0 讨论(0)
  • 2021-01-12 05:39
    use App\Http\Controllers\TargetsController;
    
    // this controller contains a function to call
    class OrganizationController extends Controller {
        public function createHolidays() {
            // first create the reference of this controller
            $b = new TargetsController();
            $mob = 9898989898;
            $msg = "i am ready to send a msg";
    
            // parameter will be same 
            $result = $b->mytesting($msg, $mob);
            log::info('my testing function call with return value' . $result);
        }
    }
    
    // this controller calls it
    class TargetsController extends Controller {
        public function mytesting($msg, $mob) {
            log::info('my testing function call');
            log::info('my mob:-' . $mob . 'my msg:-' . $msg);
            $a = 10;
            return $a;
        }
    }
    
    0 讨论(0)
提交回复
热议问题