how can i use laravel multi-database? - php

I want to know about the laravel multiple databases. is it possible to use a default database which use only user login and after login separate group by group and every group use independent database. such as 'db' is the default database it's only for the all user login.
Example: Now 'John' is login using default database 'db'. John is the member of group1 after login john use 'db1' where stored John's all type of data. Other side Now 'Alex' login using default database 'db'. Alex is the member of group2 after login Alex use 'db2' where stored Alex's all type of data. After login default db connection no need so i want to replace 'bd' to 'db1' or 'db' to 'db2'. Please provide code for laravel

Define a separate database connection in config/database.php.
'mysql' => [ // default
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
...
],
'db1' => [ // another
'driver' => 'mysql',
'host' => env('DB_HOST_ONE', '127.0.0.1'),
'port' => env('DB_PORT_ONE', '3306'),
'database' => env('DB_DATABASE_ONE', 'forge'),
'username' => env('DB_USERNAME_ONE', 'forge'),
'password' => env('DB_PASSWORD_ONE', ''),
...
]
Note that you have to define respective config in your .env.
Then when you want to use db1 connection it, use Config::set('database.default', 'db1'). However, it only works when you have known amount of database connections(that you can define in config/database.php), if you have unknown amount of databases, then you should change the config directly instead of the name of the connection only.
Example:
Config::set('database.connections.mysql.database', 'db1')
Config::set('database.connections.mysql.username', 'admin');
Config::set('database.connections.mysql.password', 'secret');
You can see my another answer to know how does it work underhood.

In this case, I presume you are building a system that is connecting to various existing databases possibly from different applications.
You can define as many DB connections as you want in your config/database.php
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
'mysql2' => [
'driver' => 'mysql',
'host' => env('DB_HOST_2', '127.0.0.1'),
'port' => env('DB_PORT_2', '3306'),
'database' => env('DB_DATABASE_2', 'forge'),
'username' => env('DB_USERNAME_2', 'forge'),
'password' => env('DB_PASSWORD_2', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
...
You would however also need a way to specify for each user which other external DB from which their details are going to be fetched from, for instance a column db_name on the users table.
At the point of fetching the data of say 'Alex' User model, you can do something like
$user = User::find(1); //if Alex has user_id 1 and where $user->db_name is 'mysql2' as is in the config/database.php file
$userDetails = DB::connection($user->db_name)->where('username',$user->name)->where('other_details','some details')->get();
Make sure to specify this in your .env too, to match what's defined in config/database.php
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
DB_HOST_2=127.0.0.1
DB_PORT_2=3306
DB_DATABASE_2=db2_name_here
DB_USERNAME_2=db2_username_here
DB_PASSWORD_2=db2_password_here
...

Related

Not able to connect Laravel app to database which is hosted on Azzure over ssl

I am struggling in connecting Laravel app with MYSQL database. I can connect to database over MySQL Workbench and also with PDO connection custom string but with Laravel I cannot. Not sure what is wrong.
Custom connection string: It works file is inside laravel app. I put this just for checking
$conn = mysqli_init();
mysqli_ssl_set($conn,NULL,NULL, "BaltimoreCyberTrustRoot.crt.pem", NULL, NULL) ;
mysqli_real_connect($conn, 'sever.host', 'server-username', 'server-password', 'database', 3306, MYSQLI_CLIENT_SSL);
if (mysqli_connect_errno($conn)) {
die('Failed to connect to MySQL: '.mysqli_connect_error());
}
else{
echo "Connected";
}
Then I added in .env file following, beside defining username password host and db name.
BaltimoreCyberTrustRoot.crt.pem file is on same path as .env file
MYSQL_SSL_KEY=BaltimoreCyberTrustRoot.crt.pem
MYSQL_SSL_CERT=BaltimoreCyberTrustRoot.crt.pem
MYSQL_SSL_CA=BaltimoreCyberTrustRoot.crt.pem
MYSQL_SSL_CIPHER=BaltimoreCyberTrustRoot.crt.pem
MYSQL_SSL=true
In config/database.php looks like this
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
'options' => (env('MYSQL_SSL')) ? [
PDO::MYSQL_ATTR_SSL_KEY => env('MYSQL_SSL_KEY'), // /path/to/key.pem
PDO::MYSQL_ATTR_SSL_CERT => env('MYSQL_SSL_CERT'), // /path/to/cert.pem
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_SSL_CA'), // /path/to/ca.pem
PDO::MYSQL_ATTR_SSL_CIPHER => env('MYSQL_SSL_CIPHER')
] : [],
Not sure what is wrong, any idea?
I get these errors:
"error":"SQLSTATE[HY000] [2002] An attempt was made to access a socket in a way forbidden by its access permissions.
[{"file":"D:\home\site\wwwroot\vendor\laravel\framework\src\Illuminate\Database\Connection.php","line":624,"function":"runQueryCallback","class":"Illuminate\Database\Connection","type":"->","args":["select * from backend_token limit 1",[],{}]},
It helps to know which version of Laravel you are on to be absolutely sure, but on Laravel 8 my database config has:
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
Don't change your database.php config but in your .env add MYSQL_ATTR_SSL_CA=/path/to/BaltimoreCyberTrustRoot.crt.pem
FYI sometimes if you are using private IP addresses then edit your hosts file
10.10.10.10 hostname.domain.com
Where of course the ip number matches the ip of the host.
If that doesn't work, add the cipher line from you config PDO::MYSQL_ATTR_SSL_CIPHER => env('MYSQL_SSL_CIPHER'),

How to update database name and set persistent connect for entire session laravel 5.5?

I have secondary connection that comes dynamically and here is it's code
'userdb' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => DYNAMIC_DATABASE_NAME,
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => false,
],
So, once use logged in I want to update update this database dynamically and reconnect to this userdb.
I have used following code but this is not giving persistent DB connection I have to this this everytime manually.
Any suggestions ?
DB::purge('userdb');
config(['database.connections.userdb.database' => 'test']);
DB::reconnect('userdb');
DB::connection('userdb');
1.first set database name
\Config::set('database.connections.userdb.database','test');
2.after set database name you need to purge the DB cache
\DB::purge('userdb');
3.set default connection after u purge db cache
\DB::setDefaultConnection('userdb');

SQL SSL errors when deploying laravel project to azure

I deployed the project to azure and both the webpage displays properly and links work fine, but for the user registration I need to connect the database. Everything works well locally and I followed all the instructions of creating/connecting a sqsl db in azure but I get thte following 3 errors and not sure what to do, how to debug, its a project I was given to deply and didnt create myself,( I am only gona show the first 3 lines of the error since they are long):
UPDATE: It works if I disable the SSL on azure so its got something to do with my local app config for that
1-
SQLSTATE[HY000] [9002] SSL connection is required. Please specify SSL options and retry. (SQL: select count(*) as aggregate from `users` where `email` = ***#***.com)
in Connection.php line 647
at Connection->runQueryCallback('select count(*) as aggregate from `users` where `email` = ?', array('***#***.com'), object(Closure))
in Connection.php line 607
2-
(2/3) PDOException
SQLSTATE[HY000] [9002] SSL connection is required. Please specify SSL options and retry.
in PDOConnection.php line 50
at PDOConnection->__construct('mysql:host=***.mysql.database.azure.com;port=**+;dbname=uwiredb', '***#***', 'MySQLAzure2017', array(0, 2, 0, false, false))
in Connector.php line 65
at Connector->createPdoConnection('mysql:host=***.mysql.database.azure.com;port=***;dbname=***', '***#***', 'MySQLAzure2017', array(0, 2, 0, false, false))
in Connector.php line 44
3-
(1/3) PDOException
SQLSTATE[HY000] [9002] SSL connection is required. Please specify SSL options and retry.
here is the DB section of my .env file:
DB_CONNECTION=mysql
DB_HOST=mydbserver.mysql.database.azure.com
DB_DATABASE=mydb
DB_USERNAME=myuser
DB_PASSWORD=mypass
MYSQL_SSL=true
And here is the connection part of my database.php file in the config folder, I know the hosts
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
],
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'homestead'),
'username' => env('DB_USERNAME', 'homestead'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
'sslmode' => env('DB_SSLMODE', 'prefer'),
'options' => (env('MYSQL_SSL')) ? [
PDO::MYSQL_ATTR_SSL_KEY => '/ssl/BaltimoreCyberTrustRoot.crt.pem',
] : [],
],
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
'sslmode' => 'prefer',
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
],
],
I know the host is set to local but that is how I understood it should be from the azure docs that say:
You can use the PHP getenv method to access the settings. the Laravel code uses an env wrapper over the PHP getenv. For example, the MySQL configuration in config/database.php looks like the following code:
PHP
Copy
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
...
],
Thanks

connect laravel to another instance of MySQL

I have 2 instances of running MySQLs on different ports (3333 and 3306)
image from workbench
my laravel project is dealing with the one in port 3333
by using these codes
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3333
DB_DATABASE=bglee
DB_USERNAME=root
DB_PASSWORD=
I'd like now to make it deal with port 3306
I edited the above codes to
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=bglee
DB_USERNAME=root
DB_PASSWORD=
but now he still works with the first port (3333)
in case running php artisan migrate , it creates the tables in the first instance (3333)
unfortunately I want Laravel to deal with the second one (3306)
because it has updated version of MySQL
contents of config/database.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => env('DB_CONNECTION', 'mysql'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
],
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
'sslmode' => 'prefer',
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => [
'client' => 'predis',
'default' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => 0,
],
],
];
There's some information about this on the Laravel documentation, as seen here for version 5.6:
https://laravel.com/docs/5.6/database#using-multiple-database-connections
So, in your config/database.php file, you'd create another connection that mirrors your original one, but with the correct port, maybe like this:
...
'connections' => [
...
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
'mysql_2' => [
'driver' => 'mysql',
'host' => env('DB_HOST_2', '127.0.0.1'),
'port' => env('DB_PORT_2', '3306'),
'database' => env('DB_DATABASE_2', 'forge'),
'username' => env('DB_USERNAME_2', 'forge'),
'password' => env('DB_PASSWORD_2', ''),
'unix_socket' => env('DB_SOCKET_2', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
...
],
Then, in your .env file, you can put the following values:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=bglee
DB_USERNAME=root
DB_PASSWORD=
DB_CONNECTION_2=mysql_2
DB_HOST_2=127.0.0.1
DB_PORT_2=3333
DB_DATABASE_2=bglee
DB_USERNAME_2=root
DB_PASSWORD_2=
And finally, you can migrate to a specific database using php artisan migrate --database=mysql_2.
Not sure if this is the BEST way to do it for your situation, but that's how I would try and approach it.

Rapid Authentication and Configuration in Laravel 5.4

I'm trying to add authentication to my Laravel project. My database configuration is:
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
And the .env file contains:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=example
DB_USERNAME=root
DB_PASSWORD=
When I try to register, this error happens:
I'm using XAMPP and my phpMyAdmin table structure is shown in this picture:
Its because remember_token field is not allowing to store null.
so either you need to provide value for remember_token or allow remember_token to have null values.

Categories