Home >Backend Development >PHP Tutorial >How to Access a Controller Method from Another Controller in Laravel 5?
How to Access a Controller Method from Another Controller in Laravel 5
When working with multiple controllers in Laravel, you may need to access a method from one controller within another. Here are various approaches to achieve this:
Using App::call() Method
You can access the method using the app() helper function:
<code class="php">app('App\Http\Controllers\PrintReportController')->getPrintReport();</code>
However, this approach is not recommended due to organizational concerns.
Extending the Controller
You can inherit the method by extending the other controller:
<code class="php">class SubmitPerformanceController extends PrintReportController { // .... }</code>
This will inherit all methods from PrintReportController, which may not be desirable.
Using Traits
The preferred approach is to create a trait with the desired logic:
<code class="php">trait PrintReport { public function getPrintReport() { // ..... } }</code>
Then, include the trait in the relevant controllers:
<code class="php">class PrintReportController extends Controller { use PrintReport; } class SubmitPerformanceController extends Controller { use PrintReport; }</code>
This allows both controllers to access the getPrintReport() method through $this->getPrintReport().
The above is the detailed content of How to Access a Controller Method from Another Controller in Laravel 5?. For more information, please follow other related articles on the PHP Chinese website!