Access Controller Method from Another Controller in Laravel 5
When working with multiple controllers in Laravel, it may be necessary to access methods from one controller within another. This can be achieved through various approaches, each with its own advantages and disadvantages.
Direct Access
One method is direct access, which involves passing the name of the controller and the method that you wish to call as arguments to the app() function. For instance, in the SubmitPerformanceController, you can access the getPrintReport() method of the PrintReportController as follows:
<code class="php">$result = app('App\Http\Controllers\PrintReportController')->getPrintReport();</code>
While this approach works, it is not considered best practice and may lead to code organization issues.
Inheritance
Another option is to inherit the PrintReportController within the SubmitPerformanceController, allowing you to access the getPrintReport() method directly. However, this approach also inherits all other methods from the parent controller, which may not be desirable.
<code class="php">class SubmitPerformanceController extends PrintReportController { // ... }</code>
Traits
A more elegant solution involves using traits. Create a trait containing the desired method (e.g., app/Traits/PrintReport.php) and implement the logic there. Subsequently, include the trait in the SubmitPerformanceController and PrintReportController using the use keyword.
<code class="php">trait PrintReport { public function getPrintReport() { // Logic here } } class PrintReportController extends Controller { use PrintReport; } class SubmitPerformanceController extends Controller { use PrintReport; }</code>
By leveraging traits, both controllers can access the getPrintReport() method using $this->getPrintReport(). This approach promotes code reusability and better organization.
The above is the detailed content of How to Access Controller Methods from Another Controller in Laravel 5?. For more information, please follow other related articles on the PHP Chinese website!