Home > Article > Backend Development > How Can I Access Methods from One Controller in Another Controller in Laravel 5?
When working with multiple controllers in Laravel, there may be scenarios where you need to access a method from one controller within another. This can be achieved through various techniques, as outlined below.
This approach involves accessing the controller method directly using the App facade:
<code class="php">app('App\Http\Controllers\PrintReportController')->getPrintReport();</code>
While this works, it is not recommended for code organization purposes.
Another option is to inherit the controller containing the desired method. For example, if SubmitPerformanceController needs to access the getPrintReport method from PrintReportController:
<code class="php">class SubmitPerformanceController extends PrintReportController { // ... }</code>
However, this approach may lead to inheritance of unnecessary methods.
Traits are a preferred solution for sharing common functionality between controllers without the drawbacks of inheritance. Here's how to use traits:
Create a Trait
Define a trait in app/Traits:
<code class="php">trait PrintReport { public function getPrintReport() { // ... } }</code>
Include the Trait in Controllers
Add the trait to both controllers:
<code class="php">class PrintReportController extends Controller { use PrintReport; } class SubmitPerformanceController extends Controller { use PrintReport; }</code>
With this approach, both controllers can access the getPrintReport method via $this->getPrintReport().
The above is the detailed content of How Can I Access Methods from One Controller in Another Controller in Laravel 5?. For more information, please follow other related articles on the PHP Chinese website!