Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 202
Paulo Coghi Avatar asked Apr 20 '15 14:04

Paulo Coghi


People also ask

Can we call method from one controller to another controller?

Yes, you can call a method of another controller. The controller is also a simple class. Only things are that its inheriting Controller Class. You can create an object of the controller, but it will not work for Routing if you want to redirect to another page.

Can we call one controller from another controller in Salesforce?

Controllers are apex classes so you just need to instantiate your second controller in the first, set whatever data you need to set and then call the method like any other class.


1 Answers

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.

like image 190
Sean Fahey Avatar answered Nov 19 '22 17:11

Sean Fahey