I need to connect to different databases, but I need to do it directly in the query without having to specify connection information in laravel's database.php file, if possible?
This is my code:
public function prueba()
{
try {
$data = Mesa::on([
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => '127.0.0.1',
'port' => '3306',
'database' => 'mydatabase_laravel',
'username' => 'root',
'password' => '',
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci'
])->get();
return $data;
} catch (Exception $e) {
error_log($e);
return Responses::errorHttpXWithoutErrors(500, 'OcurriĆ³ un error al asignar las notas');
}
}
This is the error that gives me:
str_ends_with(): Argument #1 ($haystack) must be of type string, array given
I tried to do it the way I show it in the code I attached, but it still doesn't work.
The Model::on
method accepts a connection name as a string, and not an array of DB parameters.
You could just add a configuration setup to the config file on the fly like mentioned here:
What happens here is that you just access the database config file array and then append the params to the array, and ask for it immediately after that. So you're not opening the file itself, and changes are only for one call.
If, for some reason, you can't even do that, I would consider using Vanilla PHP and connect to the DB via the standard PHP PDO way of doing it (though it is ugly and you loose Laravel's ORM and such):
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'myusername';
$password = 'mypassword';
$pdo = new PDO($dsn, $username, $password);