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

olliejjc16's avatar

Test returns error instead of 403 on API role check

Hi I’m running a test where the wrong user type with the wrong role BAdmin is trying to access an api call with role SchoolAdmin. It should return a 403 status error but I’m getting a different error instead. I think it has to do with the way my EnsureUserHasRole.php middleware is setup from trying to troubleshoot the error as it mentions the abort(403) in the file, tried changing it a few different ways but no luck

Api Call:

Route::middleware(['auth', 'role:SchoolAdmin'])->group(function () {
    Route::post("/teacher/register", [RegisteredUserController::class, 'storeTeacher']);
});

Test:

public function test_teachers_registration_with_invalid_user_permission(){

        $this->withoutExceptionHandling();

        $bAdmin = BAdmin::factory();
        $user = User::factory()
                    ->has($bAdmin, 'bAdmin')
                    ->create(['role' => 'BAdmin']);

        $this->assertGuest();

        $response = $this->actingAs($user)->post('/api/teacher/register', [
            'fullName' => 'Test Teacher',
            'userName' => 'Test Teacher UserName',
            'email' => '[email protected]',
            'password' => 'password',
        ]);

        $this->assertAuthenticated();
        $response->assertStatus(403);
    }

EnsureUserHasRole Middleware:

class EnsureUserHasRole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next, string $role)
    {
        $userId = auth()->user()->id;
        $user = User::where('id', $userId)->first();

        if ($user->role === $role) {
            return $next($request);
        }
        abort(403);
    }
}

Error:

Symfony\Component\HttpKernel\Exception\HttpException at C:\laragon\bob\BobWebApp\vendor\laravel\framework\src\Illuminate\Foundation\Application.php:1116
 if ($code == 404) {
throw new NotFoundHttpException($message);
}
throw new HttpException($code, $message, null, $headers);
}
/**
* Register a terminating callback with the application.
1   C:\laragon\bob\BobWebApp\vendor\laravel\framework\src\Illuminate\Foundation\helpers.php:44
      Illuminate\Foundation\Application::abort("", [])

  2   C:\laragon\bob\BobWebApp\app\Http\Middleware\EnsureUserHasRole.php:26
      abort()
0 likes
1 reply
tykus's avatar
tykus
Best Answer
Level 104

Remove the withoutExceptionHandling line to allow the framework respond with the 403 status code

1 like

Please or to participate in this conversation.