Access Controller method from another controller in Laravel 5
I have two controllers SubmitPerformanceController
and PrintReportController
.
In PrintReportController
I have a method called getPrintReport
.
How to access this method in SubmitPerformanceController
?
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.
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.