Can we exclude a custom service provider when running php artisan migrate in laravel?

661 views Asked by At

I have a custom service provider in which I am accessing a model in boot(). But when I run php artisan migrate, it shows the below error:

[Illuminate\Database\QueryException] SQLSTATE[42S02]: Base table or view not found: 1146 Table '********' doesn't exist

I found that if we add if (!app()->runningInConsole()) { inside boot(), it works successfully.

This is the code we have used in the service provider:

public function boot()
{
    $this->bindCurrentPartToNav();
}
private function bindCurrentPartToNav(): void
{
    $currentPartName = \App\Http\Helpers\Part::getPartName();

    view()->composer(
        'includes.partials.part',
        function ($view) use ($currentPartName) {
            $view->with('currentPartName', $currentPartName);
        }
    );
}

Helper file:

public static function getPartName(): ?string
{
    return PartModel::PartKey()->active()->pluck('name')->first();
}

Model:

public function scopePartKey($query): Builder
{
    return $query->where('identifier', config('env.PART_KEY'));
}

Is there any way to remove that service provider from php artisan migrate so that we can remove runningInConsole() check in each refresh?

Thanks for your help in advance. enter image description here

1

There are 1 answers

0
N69S On

As any environment configuration, in your case a general configuration, you should assign a default value fall back.

public static function getSectionName(): ?string
{
    try {
        return SectionModel::sectionKey()->active()->value('name');
    } catch (\Exception $e) {
        return null;
    }
}

This will simulate the case where the section model with that specific identification_key is missing in the database.

This will also prevent any issues with the initial migration.

But in the end, you tied a model with a view rendering code. You should find another solution to dissociate them. For example, you can move the boot() code out of the model and link it to a middleware.

You can also use Singleton pattern (since it's like a general unique config across the application)