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

stanislasmm's avatar

Query in service constructor

Hello,

I'm facing a problem with a query in a service constructor. I use this service to connect an API, and in this constructor I get the token which is in my database.

This way, I don't have to fetch the token every times I want to fetch data from this API in other services.

However, when I pushed my code on a dev server, php artisan migrate can't run because table which store this token is not yet created.

I found that the problem come from Laravel service providers. They get instantiated when running artisan.

It's very annoying because I have to put away this usefull token initalialization form constructor and call it every time I want to use my service.

Any one has an idea to handle this ? Am I doing something wrong ?

0 likes
2 replies
MichalOravec's avatar

Put your code inside runningInConsole

use Illuminate\Support\Facades\App;

if (! App::runningInConsole()) {
    // your code
}
1 like
martinbean's avatar

@stanislasmm Yeah, I wouldn’t have queries being executed in a class’s constructor, for this very reason. A constructor should just set the class up with what it needs; the token should only be fetched the very first time it’s needed, so I understand what you’re trying to do.

Instead, consider adding a protected method to your class that, when called, checks a token property and returns it, or fetches the token from the service and assigns it to the property if it’s not set:

protected function getToken()
{
    if (! $this->token) {
        // Get $token from service
        $this->token = $token;
    }

    return $this->token;
}

Then, you can use this method in your class’s other methods, knowing that the token will only be fetched once and fetched only the first time it’s needed:

public function someMethod()
{
    $token = $this->getToken();

    // Do API request with $token
}
2 likes

Please or to participate in this conversation.