235

I have two controllers SubmitPerformanceController and PrintReportController.

In PrintReportController I have a method called getPrintReport.

How to access this method in SubmitPerformanceController?

Iftakharul Alam
  • 3,201
  • 4
  • 21
  • 33

17 Answers17

473

You can access your controller method like this:

app('App\Http\Controllers\PrintReportController')->getPrintReport();

This will work, but it's bad in terms of code organisation (remember to use the right namespace for your PrintReportController)

You can extend the PrintReportController so SubmitPerformanceController will inherit that method

class SubmitPerformanceController extends PrintReportController {
     // ....
}

But this will also inherit all other methods from PrintReportController.

The best approach will be to create a trait (e.g. in app/Traits), implement the logic there and tell your controllers to use it:

trait PrintReport {

    public function getPrintReport() {
        // .....
    }
}

Tell your controllers to use this trait:

class PrintReportController extends Controller {
     use PrintReport;
}

class SubmitPerformanceController extends Controller {
     use PrintReport;
}

Both solutions make SubmitPerformanceController to have getPrintReport method so you can call it with $this->getPrintReport(); from within the controller or directly as a route (if you mapped it in the routes.php)

You can read more about traits here.

mustaccio
  • 18,234
  • 16
  • 48
  • 57
Sh1d0w
  • 9,340
  • 3
  • 24
  • 35
52

If you need that method in another controller, that means you need to abstract it and make it reusable. Move that implementation into a service class (ReportingService or something similar) and inject it into your controllers.

Example:

class ReportingService
{
  public function getPrintReport()
  {
    // your implementation here.
  }
}
// don't forget to import ReportingService at the top (use Path\To\Class)
class SubmitPerformanceController extends Controller
{
  protected $reportingService;
  public function __construct(ReportingService $reportingService)
  {
     $this->reportingService = $reportingService;
  }

  public function reports() 
  {
    // call the method 
    $this->reportingService->getPrintReport();
    // rest of the code here
  }
}

Do the same for the other controllers where you need that implementation. Reaching for controller methods from other controllers is a code smell.

matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
Davor Minchorov
  • 2,018
  • 1
  • 16
  • 20
41

Calling a Controller from another Controller is not recommended, however if for any reason you have to do it, you can do this:

Laravel 5 compatible method

return \App::call('bla\bla\ControllerName@functionName');

Note: this will not update the URL of the page.

It's better to call the Route instead and let it call the controller.

return \Redirect::route('route-name-here');
Mahmoud Zalt
  • 30,478
  • 7
  • 87
  • 83
  • 9
    Why is it not recommended? – brunouno Aug 24 '19 at 20:11
  • @Mahmoud Zalt where is the link of cite?? – francisco Oct 20 '21 at 14:41
  • 2
    calling a controller action is not the same as redirect, so it is not "better". – Kat Lim Ruiz Nov 02 '21 at 03:56
  • About the not recommended, my opinion is because you are "skipping" many initialization or internal Laravel logic (which may not exist now, but in the future it will). Indeed you should not. – Kat Lim Ruiz Nov 02 '21 at 03:57
  • @KatLimRuiz Even if it doesn't skip initialization steps, calling the controller this way is slower compared to a direct instantiation of a class, because of so many internal calls. Instead, one should chunk the logic into smaller classes and call those instead. – Binar Web Nov 15 '21 at 12:03
18

First of all, requesting a method of a controller from another controller is EVIL. This will cause many hidden problems in Laravel's life-cycle.

Anyway, there are many solutions for doing that. You can select one of these various ways.

Case 1) If you want to call based on Classes

Way 1) The simple way

But you can't add any parameters or authentication with this way.

app(\App\Http\Controllers\PrintReportContoller::class)->getPrintReport();

Way 2) Divide the controller logic into services.

You can add any parameters and something with this. The best solution for your programming life. You can make Repository instead Service.

class PrintReportService
{
    ...
    public function getPrintReport() {
        return ...
    }
}

class PrintReportController extends Controller
{
    ...
    public function getPrintReport() {
        return (new PrintReportService)->getPrintReport();
    }
}

class SubmitPerformanceController
{
    ...
    public function getSomethingProxy() {
        ...
        $a = (new PrintReportService)->getPrintReport();
        ...
        return ...
    }
}

Case 2) If you want to call based on Routes

Way 1) Use MakesHttpRequests trait that used in Application Unit Testing.

I recommend this if you have special reason for making this proxy, you can use any parameters and custom headers. Also this will be an internal request in laravel. (Fake HTTP Request) You can see more details for the call method in here.

class SubmitPerformanceController extends \App\Http\Controllers\Controller
{
    use \Illuminate\Foundation\Testing\Concerns\MakesHttpRequests;
    
    protected $baseUrl = null;
    protected $app = null;

    function __construct()
    {
        // Require if you want to use MakesHttpRequests
        $this->baseUrl = request()->getSchemeAndHttpHost();
        $this->app     = app();
    }

    public function getSomethingProxy() {
        ...
        $a = $this->call('GET', '/printer/report')->getContent();
        ...
        return ...
    }
}

However this is not a 'good' solution, too.

Way 2) Use guzzlehttp client

This is the most terrible solution I think. You can use any parameters and custom headers, too. But this would be making an external extra http request. So HTTP Webserver must be running.

$client = new Client([
    'base_uri' => request()->getSchemeAndhttpHost(),
    'headers' => request()->header()
]);
$a = $client->get('/performance/submit')->getBody()->getContents()
AdHorger
  • 470
  • 6
  • 13
kargnas
  • 332
  • 3
  • 10
16

You shouldn’t. It’s an anti-pattern. If you have a method in one controller that you need to access in another controller, then that’s a sign you need to re-factor.

Consider re-factoring the method out in to a service class, that you can then instantiate in multiple controllers. So if you need to offer print reports for multiple models, you could do something like this:

class ExampleController extends Controller
{
    public function printReport()
    {
        $report = new PrintReport($itemToReportOn);
        return $report->render();
    }
}
Martin Bean
  • 38,379
  • 25
  • 128
  • 201
15
\App::call('App\Http\Controllers\MyController@getFoo')
hichris123
  • 10,145
  • 15
  • 56
  • 70
the_hasanov
  • 782
  • 7
  • 15
  • 19
    Despite the fact that your answer might be correct, it would be nice to extend it a little and give some more explanation. – scana Mar 13 '16 at 14:55
15

This approach also works with same hierarchy of Controller files:

$printReport = new PrintReportController;

$prinReport->getPrintReport();
Jay Marz
  • 1,861
  • 10
  • 34
  • 54
  • I like this approach compared to the App::make one because the type hinting of the doc blocks still work in phpStorm this way. – Floris Jun 24 '20 at 07:14
  • @Floris to use type hinting, use it like this `App::make(\App\Http\Controllers\YouControllerName::class)` – Binar Web Aug 06 '21 at 09:38
5
namespace App\Http\Controllers;

//call the controller you want to use its methods
use App\Http\Controllers\AdminController;

use Illuminate\Http\Request;

use App\Http\Requests;

class MealController extends Controller
   {
      public function try_call( AdminController $admin){
         return $admin->index();   
    }
   }
matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
Ahmed Mahmoud
  • 1,724
  • 1
  • 17
  • 21
  • 11
    Please edit with more information. Code-only and "try this" answers are discouraged, because they contain no searchable content, and don't explain why someone should "try this". – abarisone Sep 19 '16 at 14:01
3

You can use a static method in PrintReportController and then call it from the SubmitPerformanceController like this;

namespace App\Http\Controllers;

class PrintReportController extends Controller
{

    public static function getPrintReport()
    {
      return "Printing report";
    }


}



namespace App\Http\Controllers;

use App\Http\Controllers\PrintReportController;

class SubmitPerformanceController extends Controller
{


    public function index()
    {

     echo PrintReportController::getPrintReport();

    }

}
2

Here the trait fully emulates running controller by laravel router (including support of middlewares and dependency injection). Tested only with 5.4 version

<?php

namespace App\Traits;

use Illuminate\Pipeline\Pipeline;
use Illuminate\Routing\ControllerDispatcher;
use Illuminate\Routing\MiddlewareNameResolver;
use Illuminate\Routing\SortedMiddleware;

trait RunsAnotherController
{
    public function runController($controller, $method = 'index')
    {
        $middleware = $this->gatherControllerMiddleware($controller, $method);

        $middleware = $this->sortMiddleware($middleware);

        return $response = (new Pipeline(app()))
            ->send(request())
            ->through($middleware)
            ->then(function ($request) use ($controller, $method) {
                return app('router')->prepareResponse(
                    $request, (new ControllerDispatcher(app()))->dispatch(
                    app('router')->current(), $controller, $method
                )
                );
            });
    }

    protected function gatherControllerMiddleware($controller, $method)
    {
        return collect($this->controllerMidlleware($controller, $method))->map(function ($name) {
            return (array)MiddlewareNameResolver::resolve($name, app('router')->getMiddleware(), app('router')->getMiddlewareGroups());
        })->flatten();
    }

    protected function controllerMidlleware($controller, $method)
    {
        return ControllerDispatcher::getMiddleware(
            $controller, $method
        );
    }

    protected function sortMiddleware($middleware)
    {
        return (new SortedMiddleware(app('router')->middlewarePriority, $middleware))->all();
    }
}

Then just add it to your class and run the controller. Note, that dependency injection will be assigned with your current route.

class CustomController extends Controller {
    use RunsAnotherController;

    public function someAction() 
    {
        $controller = app()->make('App\Http\Controllers\AnotherController');

        return $this->runController($controller, 'doSomething');
    }
}
matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
Anton
  • 422
  • 4
  • 7
2

You can access the controller by instantiating it and calling doAction: (put use Illuminate\Support\Facades\App; before the controller class declaration)

$controller = App::make('\App\Http\Controllers\YouControllerName');
$data = $controller->callAction('controller_method', $parameters);

Also note that by doing this you will not execute any of the middlewares declared on that controller.

Abhijeet Navgire
  • 683
  • 7
  • 20
  • Clean solution, thanks! Shouldn't be the way in a normal Laravel app, but in Themosis it is brilliant. Note that `$parameters` must be an array, even if there's only one or no parameters to the `controller_method`. – Bence Szalai Oct 12 '20 at 22:41
1
//In Controller A <br >
public static function function1(){

}


//In Controller B, View or anywhere <br>
A::function1();
Srilal Sachintha
  • 1,335
  • 1
  • 12
  • 18
  • 2
    Welcome to SO! Thank you for your time in answering this question. Can you please give more details about your solution? For example, why is your solution better than the accepted answer? Also, the question was asked and answered 5 years ago. Be sure to look at the date of the original question when answering. Please read [How to Answer](https://stackoverflow.com/help/how-to-answer). – above_c_level Aug 16 '20 at 19:11
1

Try creating a new PrintReportController object in SubmitPerformanceController and calling getPrintReport method directly.

For example lets say I have a function called "Test" in SubmitPerformanceController then I can do something like this:

public function test() { 
  $prc = new PrintReportController();
  $prc->getPrintReport();
 }
Abdullah Aman
  • 1,314
  • 11
  • 11
1

IMO the most elegant approach:

app(YourController::class)->yourControllerMethod()
Artur Müller Romanov
  • 4,417
  • 10
  • 73
  • 132
1

In SubmitPerformanceController add a constructor.

private $printReportController;
public function __construct(PrintReportController $printReportController)
{
     $this->printReportController = $printReportController;
}

Now you can call the getPrintReport function by using,

return $this->printReportController->getPrintReport();
Sreehari S
  • 11
  • 3
0
  1. Well, of course, you can instantiate the other controller and call the method you want. Probably it's not a good practice but I don't know why:
$otherController = new OtherController();
$otherController->methodFromOtherController($param1, $param2 ...);
  1. But, doing this, you will have a problem: the other method returns something like response()->json($result), and is not it what you want.

  2. To resolve this problem, define the first parameter of the other controller's method as:

public function methodFromOtherController(Request $request = null, ...
  1. When you call methodFromOtherController from the main controller, you will pass null as first parameter value:
$otherController = new OtherController();
$otherController->methodFromOtherController(null, $param1, $param2 ...);
  1. Finally, create a condition at the end of the methodFromOtherController method:
public function methodFromOtherController(Request $request = null, ...) 
{
  ...
  if (is_null($request)) {
    return $result;
  } else {
    return response()->json($result);
  }
}
  1. Once Laravel will ever set $request when it is called by direct route, you can differentiate each situation and return a correspondent value.
Doglas
  • 642
  • 1
  • 11
  • 22
-1

Late reply, but I have been looking for this for sometime. This is now possible in a very simple way.

Without parameters

return redirect()->action('HomeController@index');

With Parameters

return redirect()->action('UserController@profile', ['id' => 1]);

Docs: https://laravel.com/docs/5.6/responses#redirecting-controller-actions

Back in 5.0 it required the entire path, now it's much simpler.

Vipul Nandan
  • 97
  • 1
  • 8
  • 5
    The original question was how to access a controller's method from other controller, not how to redirect to other specific method's action, so your solution is not related to the question. – matiaslauriti May 03 '19 at 21:49