I have a Model for DB tables, basically is one table but in different databases,
How can I set a connection to DB in Model?
protected $connection = 'ls';
Above code is not that I am looking for, I need to pass host, port, username and password. because conection are stored in DB not in config file.
I was thinking for function __construct() and call like Model($data)::where()..etc
Or I am thinking wrong way, can somebody give me an better idea.?
You can connect from Eloquent model by maintaining following aspects
First you can define multiple connection in database.php file
<?php
return array(
'default' => 'mysql',
'connections' => array(
# Our primary database connection
'mysql' => array(
'driver' => 'mysql',
'host' => 'host1',
'database' => 'database1',
'username' => 'user1',
'password' => 'pass1'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
# Our secondary database connection
'mysql2' => array(
'driver' => 'mysql',
'host' => 'host2',
'database' => 'database2',
'username' => 'user2',
'password' => 'pass2'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
),
);
You have your default connection still set to mysql . This means that, unless we specify otherwise, the application will use that mysql connection.
Now in your model you can specify which connection to use
<?php
class SomeModel extends Eloquent {
protected $connection = 'mysql2';
}
You can also define the connection at runtime via the setConnection method.
<?php
class SomeController extends BaseController {
public function someMethod()
{
$someModel = new SomeModel;
$someModel->setConnection('mysql2');
$something = $someModel->find(1);
return $something;
}
}
Related
I have my laravel project deployed in heroku, but I only migrated the database that I have created eg: users, news. But I have another database that is not migrated from my laravel project. Meaning, it is a existing database and I'm only connecting it on my project. In my development stage, I can connect the second database using my codes below. But now, I will deploy my project in heroku and I dont know how can I connect the second database because in heroku's postgresSQL you can only create and migrate the database based on the migration folder in laravel. I dont know how to upload an sql file in heroku's postgresSql and in that way I can connect the second database using the codes below. Is this possible in heroku? Because the second database is important in my landing page. It includes some few select query.
Here are some of my codes including the connection of the second database.
.env
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:HoQcNyCc5KEGw4yjqpBIdKzTC+yeDoOJcerVMEVx+fs=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=adminpanel
DB_USERNAME=root
DB_PASSWORD=
DB_CONNECTION_SECOND=mysql2
DB_HOST_SECOND=127.0.0.1
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=ricjac8_orocoin
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=
database.php
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DATABASE_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],
'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'),
]) : [],
],
'mysql2' => [
'driver' => 'mysql',
'host' => env('DB_HOST_SECOND'),
'port' => env('DB_PORT_SECOND'),
'database' => env('DB_DATABASE_SECOND'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD','forge'),
'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'),
]) : [],
],
GraphController.php - The one that has select query from my other database
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\DB;
use View;
use App\News;
use Charts;
use App\Graph;
use App\Roadmap;
class GraphController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$allroad = Roadmap::all();
$news = News::all();
//the second database query
$graphdetails = Graph::select()->where('id', 1)->get();
return view('coin.news',compact('news','graphdetails','allroad'));
}
}
graph.blade.php - the result of the select query being rendered in a chart
//other blade codes i didint include here.
#foreach ($graphdetails as $item)
#endforeach
chart.legend = new am4charts.Legend();
chart.data = [{
"tokens": "Sold Tokens",
"values": {{$item->total_tokens}} - {{$item->sales_token}}
},{
"tokens": "Unsold Tokens",
"values": {{$item->sales_token}}
}];
});
Graph.php model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Auth;
use Cache;
use Charts;
class Graph extends Model
{
//
protected $connection = 'mysql2';
protected $table = 'ico_stages';
protected $fillable = [
'name', 'start_date', 'end_date', 'total_tokens', 'base_price', 'min_purchase', 'max_purchase', 'soft_cap', 'hard_cap',
'display_mode','private','user_panel_display','sales_token','sales_amount','status',
];
}
Try another free shared hosting that uses MySQL. PostreSQL is a little bit different than MySQL.
on a module I have add a component named db where i put, like the main Yii component, the data for database connection, I need in my module use everytime the db specified in his configuration for all models and not the main database connection, how I can do this?
You have several way eg. using a separated configuration in app/config/main.php
eg adding a specific dbMyMod to component config
return [
// ...
'components' => [
// ...
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=example',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
'dbMyMod ' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=hostForMudle;dbname=module_db_name',
'username' => 'user_module_name',
'password' => 'password',
'charset' => 'utf8',
],
],
or one way that not require a static configuration in app/confing
could be based on a module function that return a proper db connection
public function myModuleDbCon()
{
$myDbCon = new yii\db\Connection([
'dsn' => 'mysql:host=localhost;dbname=example',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
]);
return myDbConn;
}
then in you module you can retrive the module db connection
aDbConn = Yii::$app->getModule('my_module_name')->myModuleClass->myModuleDbCon();
.
$command = $aDbConn->createCommand('SELECT * FROM myTable');
$result= $command->queryAll();
I have two databases and want to select one database at the time of login.
I have userid: user1 in both databases and I have userid, password and database dropdown option to select database in login form, how I can achive this, by this way or some other way?
In database.php
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'abc',
'prefix' => '',
//'encoding' => 'utf8',
);
public $second = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'xyz',
'prefix' => '',
//'encoding' => 'utf8',
);
You can override the Model constructor setting the datasource as you need.
Like this
class AppModel extends Model
{
public function __construct($id = false, $table = null, $ds = null)
{
parent::__construct($id, $table, $connection_name);
$this->useDbConfig = $connection_name;
}
}
Ask me if you need more information
Currently I am using dynamic database switching in Cakephp from the database config file. I am switching based on the subdomain ie: TEST.mysite.com and PROD.mysite.com.
How and where is the best place to test and redirect if there is a database connection?
Thanks,
kSeudo
The quick and dirty way to do this is to put a condition in the constructor. I say dirty because it creates a conditional config and with the introduction of a bug could leave your production app connected to a dev database.
class DATABASE_CONFIG {
public $default = array(
'driver' => 'mysql',
'persistent' => false,
'host' => '',
'login' => '',
'password' => '',
'database' => '',
'prefix' => '',
'encoding' => 'utf8'
);
public $testDB = array(
'driver' => 'mysql',
'persistent' => false,
'host' => '',
'login' => '',
'password' => '',
'database' => '',
'prefix' => '',
'encoding' => 'utf8'
);
public function __construct()
{
if (false !== stripos($_SERVER['HTTP_HOST'], 'test'))
{ // Use the test DB since 'test' is present in the server host
$this->default = $testDB;
}
}
}
To test connection you could put the following in the contructor for app_model.php
public function __construct()
{
parent::__construct();
$db =& ConnectionManager::getDataSource('default');
if (empty($db->connection))
{
echo 'oh noes we werent able to connect';
exit;
}
}
I'm having trouble creating a page, which requires two different databases..
The controller is automaticly set to 'DB2', which is also specified in the database config file.
When i add a var $uses = array ('groups') to the controller, which is from the other DB (DB1), i get the data from only DB2 and all requests to DB1 become a invalid query..
u guys know a solution?
Thanks in advance!
Regards,
Swen
If have multiple datasources defined in your config/database.php file, you should be able to tell your Group model to use the second (non-default) config:
public $useDbConfig = 'db2';
Your config/database.php file should looks something like this:
class DATABASE_CONFIG {
var $default = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'your_host',
'login' => 'your_login_1',
'password' => 'your_password_1',
'database' => 'DB1',
'prefix' => ''
);
var $db2 = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'your_host',
'login' => 'your_login_2',
'password' => 'your_password_2',
'database' => 'DB2',
'prefix' => ''
);
}