Home / Snippets / Laravel 8 Accessing Controller Method From Another Controller
Laravel 8 Accessing Controller Method From Another Controller cover

Laravel 8 Accessing Controller Method From Another Controller

4.4K

2 years ago

0 comments

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
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this