Simple test code
Need to run middleware in controller but it doesn't work Also, if you change the middleware key with a random key, ignore it and echo only the "constructed" string
<?php namespace App\Http\Controllers; use Closure; use Illuminate\Http\Request; class RootController extends Controller { public function __construct() { $this->middleware('middleware.key'); echo 'construct<br>'; } public function test(){ return 'test'; } }
<?php namespace App\Http\Middleware; use App\Http\Controllers\Controller; use Closure; use Illuminate\Http\Request; class TestMiddleware extends Controller { public function handle(Request $request, Closure $next) { echo 'middleware'; return $next($request); } }
output is : construct test
You must register the middleware from
app/Http/Kernel.php
and add the middleware to your routes.https://laravel.com/docs/9 .x/middleware#Assign middleware to route