Home > Backend Development > PHP Tutorial > How to Access Controller Methods from Another Controller in Laravel 5?

How to Access Controller Methods from Another Controller in Laravel 5?

Susan Sarandon
Release: 2024-11-02 18:08:29
Original
763 people have browsed it

How to Access Controller Methods from Another Controller in Laravel 5?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template