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

Čamo's avatar
Level 3

API auth check inside a controller

Hi, I have an API. common way to check if user is logged in is middle in routes file like

Route::prefix('api')->middleware([ 'api', 'tenant.origin'])->group(function () {
     ... 
}

But I can not do it cause my routes are same for all users (including not logged in). But I need to check if user is logged (if JWT token is valid) in in controller. I am not sure if auth()->chcek() is enough in the case of API token check. Is there neccessary to ad some other logic or not?

Thanks.

0 likes
8 replies
Čamo's avatar
Level 3

@tisuchi Thanks but the article is based on router middleware check or on controller::__construct() middleware check. But I need to make auth check on controller methods level. It schould check inside the method and do not throw auth exception but only boolean value.

krisi_gjika's avatar

"But I can not do it cause my routes are same for all users (including not logged in)"

you can create two groups, one for guest routes and one for api routes

1 like
Čamo's avatar
Level 3

@krisi_gjika I want to avoid duplicities in router file. I rather make one method in controller which will check it.

krisi_gjika's avatar

@Čamo I do not recommend it, since it's easy for you or someone else on the team to forget to add that check for an endpoint. And you end up with an unprotected route.

Čamo's avatar
Level 3

@krisi_gjika I understand it but there will be a lot of logic which is common for all users.

Čamo's avatar
Level 3

I wrote this method which should check auth user but can not catch the exception. It throws all application out as unauthenticated.

	protected function isAuthenticated()
	{
		try {
			$this->middleware('auth:api-web-app', ['except' => []]);
		}
		catch (\Exception $e) {
			Log::info('iiiiiiiiiiiiiiiiiiiiiiiiiii');
			Log::info($e->getMessage());
		}
	}
Čamo's avatar
Level 3

So the problem is that Laravel executes middlewares after __construct() method. I thought middlewares runs first or imediatelly how they are called from constroller.

Please or to participate in this conversation.