Skip to content

[9.x] Make Connection Class Macroable#41865

Merged
taylorotwell merged 3 commits into
laravel:9.xfrom
haider00125:feature/make-connection-class-macroable
Apr 7, 2022
Merged

[9.x] Make Connection Class Macroable#41865
taylorotwell merged 3 commits into
laravel:9.xfrom
haider00125:feature/make-connection-class-macroable

Conversation

@haider00125

Copy link
Copy Markdown
Contributor

I having a use case where I have to check database connection in different service providers. I am doing it in following way:

try {
    DB::connection()->getPdo();
} catch (Exception) {
    return false;
    // Don't proceed further;
}

If connection class is macroable then above check can be simplified like below.

  DB::macro('connected', function (string $connection = null) {
            try {
                DB::connection($connection)->getPdo();
                return true;
            } catch (Exception) {
                return false;
            }
  });

Implementation:

if (DB::connected()) {
     // Do something.
}

@taylorotwell taylorotwell merged commit c195fd9 into laravel:9.x Apr 7, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants