I have a Laravel app that uses two database connections.
One is always accessible (and is the default configured in my environment).
The other one is remote and may be unreachable (that's its expected behavior).
This second database is accessible only through a button. I want this button to be enabled only if the database is reachable.
For this, I am using a simple Livewire
component that checks DB::('second_db')->getPdo();
Here is my component
// blade
<button wire:init="loadDisabled" class="..." {{ $this->disabled ? 'disabled' : '' }}>
Access DB
</button>
// Component class
public $disabled = true;
function loadDisabled()
{
try {
DB::connection('second_db')->getPdo();
} catch (PDOException $e) {
$this->disabled = true;
}
$this->disabled = false;
}
public function render()
{
return view('livewire.my-component');
}
When using Tinker, I tried DB::connection('second_db')->getPdo();
after a few seconds (a lot in my opinion), I got PDOException with message 'SQLSTATE[HY000] [335544721] Unable to complete network request to host "..."
because the db was offline (that's what I expect) but when I tried it on the web with a page containing my livewire component, I got a 504 Gateway time-out
from nginx
I even tried catching any exception with catch(Exception $e)
but the same thing happened
I digged deeper and I realized it's due to the default valet-linux
configuration.
When I searched for a solution, everyone was proposing to increase the timeout but I don't want that !
What I want to tell my program to do :
- Try for X seconds (say 5 seconds or even less) to get the pdo
- If that works, good, give me true
- If not, just throw PDOException (or whatever Exception is more appropriate for this case)
- Let me handle the exception in my
catch
block
Basically, I want my app to "decide to stop" before it triggers an nginx
error because I know for a fact that if it takes that long, it's that my db is unreachable and that's what I'm looking for.