Home  >  Q&A  >  body text

Middleware in Laravel 9 controller not working

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

P粉463811100P粉463811100211 days ago355

reply all(1)I'll reply

  • P粉649990163

    P粉6499901632024-02-26 10:50:46

    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

    reply
    0
  • Cancelreply