Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

BernardoBF4's avatar

Middleware not working

I am trying to write a test that verifies if the user is a guest trying to access a route that requires authentication, then it will. if the user is a guest, it they'll be redirected to the login route. But what I get in my test, instead of a success is the error bellow. My test, middleware, kernel, routes and error are displayed bellow.

Can someone explain me why I am receiving this error?

My middleware:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class AuthMiddleware
{
  /**
   * Handle an incoming request.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
   * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
   */
  public function handle(Request $request, Closure $next)
  {
    if (!auth()->user()) {
      return redirect(route('auth.get_login_view'), 301);
    }

    return $next($request);
  }
}

Kernel:

protected $routeMiddleware = [
   ...
    'authentication' => \App\Http\Middleware\AuthMiddleware::class,
  ];

My routes:

Route::as('auth.')->group(function () {
  Route::get('login', [AuthController::class, 'getUserTheLoginView'])->name('get_login_view');
  Route::prefix('auth')->group(function () {
    Route::post('login', [AuthController::class, 'loginUser'])->name('log_user');
  });
});

Route::middleware('authentication')->group(function () {
  Route::resources(['groups' => GroupsController::class]);
  Route::resources(['users' => UsersController::class]);
});

My test:

public function a_user_is_redirected_if_not_authenticated()
  {
    $this->withoutExceptionHandling();

    $response = $this->get(route('cms.users.index'));

    $response->assertRedirect();
  }

Error:

  • Tests\Feature\Cms\UsersTest > a user is redirected if not authenticated
  Expected response status code [201, 301, 302, 303, 307, 308] but received 200.
  Failed asserting that false is true.

  at tests/Feature/Cms/UsersTest.php:23
     19▕     $this->withoutExceptionHandling();
     20▕ 
     21▕     $response = $this->get(route('cms.users.index'));
     22▕ 
  ➜  23▕     $response->assertRedirect();
     24▕   }
     25▕ 
     26▕   /** @test */
     27▕   public function a_logged_user_can_create_another_user()


  Tests:  1 failed
  Time:   0.37s
0 likes
4 replies
Tray2's avatar

This is how I usually test that kind of middleware.

<?php

namespace Tests\Feature\Http;

use Tests\TestCase;

class AuthorizationTest extends TestCase
{
    public function protectedRoutesProvider(): array
    {
        return [
            'Authors: a guest is not authorized to visit the create page' => ['get', '/authors/create'],
            'Authors: a guest is not authorized to visit the edit page' => ['get', '/authors/1/edit'],
            'Authors: a guest is not authorized to visit the update page' => ['put', '/authors/1'],
            'Books: a guest is not authorized to visit the create page' => ['get', '/books/create'],
            'Books: a guest is not authorized to visit the edit page' => ['get', '/books/1/edit'],
            'Books: a guest is not authorized to visit the store page' => ['post', '/books'],
            'Books: a guest is not authorized to visit the update page' => ['put', '/books/1'],
            'Books: a guest is not authorized to visit the delete page' => ['delete', '/books/1'],

        ];
    }

    /**
     * @test
     * @dataProvider protectedRoutesProvider
     * @param $method
     * @param $route
     */
    public function guests_are_redirected_to_login($method, $route): void
    {
        $response = $this->$method($route);
        $response->assertLocation('/login');
    }
}
2 likes
Sinnbeck's avatar

Can you show the cms.users.index route? Any chance you meant to use users.index?

BernardoBF4's avatar

@Sinnbeck My route is this Route::resources(['users' => UsersController::class]);.

Sorry for being late, btw.

BernardoBF4's avatar
BernardoBF4
OP
Best Answer
Level 4

Found the solution. As of Laravel 9, the way that works for me is by adding the middleware to my routes as I did bellow.

Now, I don't know if this is more of a workaround rather than a solution, beacuse it's weird to have registered my middleware in the Kernel.php and also importing it and using its class.

...
use \App\Http\Middleware\AuthMiddleware;
...
Route::middleware(AuthMiddleware::class)->group(function () {
  Route::resources(['groups' => GroupsController::class]);
  Route::resources(['users' => UsersController::class]);
});

Please or to participate in this conversation.