SubjectConnection.php•2.13 kB
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
class SubjectConnection extends Model
{
protected $fillable = [
'connection_name',
'driver',
'host',
'port',
'database',
'username',
'password',
'options',
'description',
'is_active'
];
protected $casts = [
'options' => 'array',
'is_active' => 'boolean',
'port' => 'integer'
];
protected $hidden = [
'password'
];
public function getDatabaseConnection()
{
$config = [
'driver' => $this->driver,
'host' => $this->host,
'port' => $this->port,
'database' => $this->database,
'username' => $this->username,
'password' => $this->password,
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
];
if ($this->options) {
$config = array_merge($config, $this->options);
}
Config::set("database.connections.{$this->connection_name}", $config);
return DB::connection($this->connection_name);
}
public function testConnection()
{
try {
$connection = $this->getDatabaseConnection();
$connection->getPdo();
return true;
} catch (\Exception $e) {
return false;
}
}
public function executeQuery($sql, $bindings = [])
{
$connection = $this->getDatabaseConnection();
// Determine query type
$trimmedSql = trim(strtoupper($sql));
if (str_starts_with($trimmedSql, 'SELECT') ||
str_starts_with($trimmedSql, 'SHOW') ||
str_starts_with($trimmedSql, 'DESCRIBE') ||
str_starts_with($trimmedSql, 'EXPLAIN')) {
return $connection->select($sql, $bindings);
}
return $connection->statement($sql, $bindings);
}
}