In my Laravel 9 project, I have main controller -> HomeController.

Inside HomeController I have several functions where other controller is called:

class HomeController extends Controller
{
    public function callSubController()
    {   
        app('App\Http\Controllers\SubController')->SubControllerFunction();
    } 
}

​ in my SubController I want to add middleware rule SubControllerMiddleware in __construct function, but it is not working.

class SubController extends Controller
{   

  public function __construct()
    {   
        $this->middleware(['auth', 'SubControllerMiddleware']);
        
    }    
}

Is there a way how to call middleware inside SubController?

1

There are 1 best solutions below

0
On

To resolve this issue fellow these steps : 1- Define the middleware in your

app/Http/Kernel.php

file, if it's not already defined. Middleware can be global or specific to your controller or route.

// Example middleware definition
protected $routeMiddleware = [
    'customMiddleware' => \App\Http\Middleware\CustomMiddleware::class,
];

2- use it inside controller

// Apply the middleware to this method
        $this->middleware('customMiddleware');