phplaravellaravel-12

Middleware exceptions do not work in Laravel 12


I'm doing an online course to learn Laravel, and I have decided to follow it using the latest version of Laravel.

The person on the videos uses an older version of Laravel, so obviously some of the code does not work for me.

I am currently trying to add exceptions to a middleware for certain routes, but this code does not work for me:

web.php:

use App\Http\Controllers\CategoryController;
use App\Http\Middleware\ApiAuthMiddleware;    

Route::resource('/api/category', CategoryController::class)->middleware(ApiAuthMiddleware::class);

CategoryController.php:

use App\Http\Middleware\ApiAuthMiddleware;

class CategoryController extends Controller
{
   public function __construct() {
     $this->middleware(ApiAuthMiddleware::class)->except('index', 'show');
   }

   public function index(Request $request) {
      $categories = Category::all();
      return response()->json([
        'code' => 200,
        'status' => 'success',
        'categories' => $categories            
     ]);
   }
   
   public function show($id) {
      $category = Category::find($id);
      $data = [
         'code' => 200,
         'status' => 'success',
         'category' => $category
      ];
      return response()->json($data, $data['code']);
  }
}

Apparently, it does not work anymore, as the middleware runs for both routes:

Middleware runs

I have also tried this code, just to check if there is something wrong in the except code line, but I keep getting the same instead of just "hello", so apparently, the middleware runs before the construct method, which is something I don't want to happen:

public function __construct() {
  echo "hello";
  die();
  //$this->middleware(ApiAuthMiddleware::class)->except('index', 'show');
}

I have no idea what I should use as alternative. I have checked the official docs for Laravel 12, and there is nothing related to this.

The only thing I could do, is setting each route separately, instead of using resource, but I would prefer to use resource and exclude some routes from the middleware if possible, because that is what is used in the video and I think it is just cleaner.

Please, any help?


Solution

  • The syntax for putting middlewares in controllers was changed in laravel 11 or 12 I think.

    use App\Http\Middleware\ApiAuthMiddleware;
    use Illuminate\Routing\Controllers\HasMiddleware;
    use Illuminate\Routing\Controllers\Middleware;
     
    class CategoryController implements HasMiddleware
    {
        /**
         * Get the middleware that should be assigned to the controller.
         */
        public static function middleware(): array
        {
            return [
                new Middleware(ApiAuthMiddleware::class, except: ['index', 'show']),
            ];
        }
    }