I am trying to check if a database is connected in Laravel.
I've looked around the documentation and can't find anything. The closest thing I've found is this, but this doesn't solve my problem.
I have three instances of MySQL that are set up on different machines. Below is a simplified version of what I am trying to achieve.
If database 1 is connected, save data to it
If database 1 is not connected, check if database 2 is connected
If database 2 is connected save data to it
If database 2 is not connected, check if database 3 is connected
If database 3 is connected, save data to it
To be clear, is there a way to check that a database is connected in Laravel 5.1?
Try just getting the underlying PDO instance. If that fails, then Laravel was unable to connect to the database!
use Illuminate\Support\Facades\DB;
// Test database connection
try {
DB::connection()->getPdo();
} catch (\Exception $e) {
die("Could not connect to the database. Please check your configuration. error:" . $e );
}
You can use alexw's solution with the Artisan. Run following commands in the command line.
php artisan tinker
DB::connection()->getPdo();
If connection is OK, you should see
CONNECTION_STATUS: "Connection OK; waiting to send.",
near the end of the response.
You can use this, in a controller method or in an inline function of a route:
use Illuminate\Support\Facades\DB;
//....
try {
DB::connection()->getPdo();
if(DB::connection()->getDatabaseName()){
echo "Yes! Successfully connected to the DB: " . DB::connection()->getDatabaseName();
}else{
die("Could not find the database. Please check your configuration.");
}
} catch (\Exception $e) {
die("Could not open connection to database server. Please check your configuration.");
}
You can also run this:
php artisan migrate:status
It makes a db connection connection to get migrations from migrations table. It'll throw an exception if the connection fails.
You can use this query for checking database connection in laravel:
use Illuminate\Support\Facades\DB;
// ...
$pdo = DB::connection()->getPdo();
if($pdo)
{
echo "Connected successfully to database ".DB::connection()->getDatabaseName();
} else {
echo "You are not connected to database";
}
For more information, you can check out this page https://laravel.com/docs/5.0/database.
I don't know if this worked in that version of laravel, but at least on newer ones you can run
php artisan db
and if your app can access the database then you should see a cli repl for it, for postgres you will see a psql instance
Another Approach:
When Laravel tries to connect to database, if the connection fails or if it finds any errors it will return a PDOException error. We can catch this error and redirect the action
Add the following code in the app/filtes.php file.
App::error(function(PDOException $exception)
{
Log::error("Error connecting to database: ".$exception->getMessage());
return "Error connecting to database";
});
Hope this is helpful.
Related
I am using SQLSRV driver with PDO to connect MSSQL Server in Windows environment. This is quite weird issue that i am trying to run a cron job from command line like
I get fatal error saying There is no active transaction as soon as my db object tries to commit the transaction. Here is my source code
try {
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->dbh->beginTransaction();
INSERT STATEMENT 1
INSERT STATEMENT 2
..................
..................
$this->dbh->commit();
} catch (Exception $e) {
$this->dbh->rollBack();
}
In order to check this whether transaction is working or not, i simply put beginTransaction() line in if condition like this
if ($this->dbh->beginTransaction()) {
echo "Database transaction started";
else {
echo "Not started";
}
This is how pdo object look like when i print $this->dbh
PDO Object
(
)
Then control goes to else part and show Not started. The weird thing is that my cron file is located under my project which is consuming same database connection file that is used by other sections of the application (admin and front end). In the same cron file SELECT and UPDATE is working fine.
I observed that just single database instance is being created. Also database transaction is working fine for admin and front end area.
I could not get any help from Google to understand why database transaction is not working for command line execution.
Try this :
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->dbh->beginTransaction();
try {
INSERT STATEMENT 1
INSERT STATEMENT 2
..................
..................
$this->dbh->commit();
} catch (Exception $e) {
$this->dbh->rollBack();
}
I have a question regarding PHP's way to handle exceptions and Laravel 5.
Here's a snippet of what I'm trying to accomplish
try
{
//set up webservices
saveData();
} catch(exception $e)
{
Log:error('stuff went bananas')
}
saveData(){
//record stuff through DB with eloquent
//in case some data is missing connect to a second DB
try
{
connect()
query to get data
}catch(exception $e)
{
//log error again
}
In other words, I'm calling webservices that receive data. I'm then inserting these into my own DB inside the Model.
At this stage I'm trying to see if I know the user ID that I just received. In case I don't I have to connect to a second database to request that same user.
There are two issues though
the second database I'm trying to connect isn't likely to be up
it will often not hold the information I need (I have to try again the next day)
There's nothing I can do against these issues. But what I want is for my code to try and connect, and in case it fails, log the errors and keep moving inserting the data.
Thanks in advance.
First of all I don't have any database and I write code in migrations to create database, table and data, I want to check if database not exist then auto create new database have name in db connect and try catch this connect if error.
public function up()
{
try {
\DBUtil::create_database('database_name', 'utf8_general_ci', true);
// the true flag adds a IF NOT EXISTS
} catch(\Database_Exception $e) {
echo $e->getMessage();
}
}
try code but give error "Unknown database database_name" when I run "php oil refine migrate" in commandline
Can I try catch custom exception this error?
1049!
Fuel\Core\Database_Exception [ 1049 ]:
SQLSTATE[HY000] [1049] Unknown database 'database_name'
Creating a database is not something that is usually done by migrations as it would tie you in to using the same DB name all the time, if you are deploying multiple sites on the same server or have a similar scenario this becomes a big problem.
It's generally assumed that the database itself has been created as part of the set-up, either manual or automatic, so is available for PHP to connect to.
I'm new to laravel and I couldn't find an answer to the problem in the documentation nor google. So here it is:
I have to use a vpn connection to connect to the postgresql database. If I'n not connected laravel gives me the following error:
SQLSTATE[08006] [7] could not connect to server: Connection timed
out.....
How do I tell laravel to ignore that error and instead just return a message "no connection"?
$export = DB::connection('pgsql')->select("SOME SQL");
I tried the "#" before the DB, but that doesn't seem to do the trick.
Add this to your routes.php (top of it) or your start.php:
App::error(function(\Exception $e)
{
return "Error handled!";
});
And try again:
$export = DB::connection('pgsql')->select("SOME SQL");
It will catch the error and now you can do whatever you need with it.
If you return null from that error handler, Laravel will catch the error and do what it is doing now.
I am running a php gearman worker which establishes the connection to the database. However, the problem is that after around 8 hours, the mysql connection disconnects, and my worker crashes. So, I wanted to disconnect and make a new connection to the database again.
I am using CDbConnection to connect to the database in Yii, and was expecting "setActive(false)" to do the trick for me. Here below I am "explicitly disconnecting" and the making a db query....expecting my query to throw an exception, but I am surprised to see that "setActive" makes no impact at all and my query goes successfully.
//if it fails then reconnect to the database
Yii::app()->db->setActive(false);
try {
$model = MyModel::model()->findByPk(10);
var_dump($model);
} catch (exception $e) {
echo "got exception -- ".$e->getMessage()."\n";
Yii::app()->db->setActive(false);
Yii::app()->db->setActive(true);
// I also tried Yii::app()->db->active = true/false
$model = MyModel::model()->findByPk(10);
var_dump($model);
}
How do I disconnect and reconnect to my database with CdbConnection?
Try looking in the trace log, I'm pretty sure it actually closes the connection, but then reopens it in CDbConnection->createCommand() when you execute a query.