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

fkiesnh's avatar

Is it possible to add Authenticate Middleware in constructor of PHP class but not Controller

Is it possible to add Authenticate Middleware in constructor of PHP class but not Controller?

Example:

namespace App\Http\Services;

class SomeService {

    protected $token;

    public function __construct() {
        $this->middleware(function ($request, $next) {
            $this->token = \Auth::user()->profile->token;

            return $next($request);
            }
    }

    public function some_function(){
        return $this->token;
    }
}
0 likes
1 reply
tykus's avatar

Not a use case for middleware IMO. Middleware is intended to decorate requests and responses as they enter and leave your app respectively. It should be separate from your application logic.

Please or to participate in this conversation.