How to Access a Controller Method from Another Controller in Laravel 5?

Susan Sarandon
Release: 2024-10-31 08:00:30
Original
511 people have browsed it

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

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

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

Then, include the trait in the relevant controllers:

<code class="php">class PrintReportController extends Controller {
     use PrintReport;
}

class SubmitPerformanceController extends Controller {
     use PrintReport;
}</code>
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!