Posts Learn Components Snippets Categories Tags Tools new About
/

Laravel 8 Accessing Controller Method From Another Controller

Learn how to access another controller method from another controller class the easy way in Laravel 8

Created on Oct 22, 2021

35 views

To access the other controller class method from another controller you will have to get the instance from the container which is using "app()" helper method or "App::make()" facade.

Method 1: Using":app()" Helper Method


The 1st method is to use the "app()" helper method to get the other controller instance and then from the instance itself you can call the method. For this example let's say you have PostController and you want to get the method called "specialPostID()" method that returns some special ID. It might sound weird but do refer to the code below.
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostController extends Controller
{
    public function specialPostID() {
        return [1, 2, 3, 4];
    }
}
Now that you have seen the PostController code above, to call the "specialPostID()" from UserController, you can write it like below.
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function show() {
        $specialIDS = app('App\Http\Controllers\PostController')->specialPostID();

        dd($specialIDS); // [1, 2, 3, 4]
    }
}

Using App::make() Facade


Just like the "app()" helper method like above, you can also make use of the "App" facade and call in the "make()" method.
<?php

$specialIDS = App::make('App\Http\Controllers\PostController')->specialPostID();

dd($specialIDS); // [1, 2, 3, 4]

Other Reads

  • How to get Service Container in Laravel

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)