How to connect two database in laravel-5 and how to get data from db.
I know two one thing for that
In config/database set like this.
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'larashop'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
'mysql2' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'larashop2'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
Using Query you can define a connection on the Query Builder:
$users = DB::connection('mysql2')->select('your query');
Using Eloquent
You can also define which connection to use in your Eloquent models as well!
<?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;
}
}
I have find the issue of connect 2 database in laravel.
If any body wants two work with 2 database then config as par above suggestion and remove database configuration from .env file which is located at root.
I have tried and I am working with 2 database.
Related
I'm developing a Multi Tenant with Laravel v5.7 and I'm successful in sending queue emails, since my models have the property 'connection' defined.
But when trying to send, for example, an email using the Jobs class, the same fails and informs that the table of model does not exist.
From what error recorded in the table 'failed_jobs', even with the property 'connection' defined, it appears that the Job nevertheless tries to connect to the main database and not to the specified database of the property.
Is there any way to specify in Job which database to use, since the same is informed in the model?
database.php
'connections' => [
'others' => ['...']
'TENANT001' => [
'driver' => 'mysql',
'database' => env('TENANT001_DATABASE', ''),
'host' => env('TENANT001_HOSTNAME', ''),
'port' => env('DB_PORT', '3306'),
'username' => env('TENANT001_USERNAME', 'forge'),
'password' => env('TENANT001_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
],
Sample Model
class Template extends Model
{
/**
* The database name used by the model.
*
* #var string
*/
protected $connection = 'TENANT001';
}
failed_jobs
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'main_database.templates' doesn't exist in /www/samba/laravel.local/vendor/laravel/framework/src/Illuminate/Database/Connection.php:326
I guess you are trying to access second connection TENANT001 in Template Model.
class Template extends Model
{
/**
* The database name used by the model.
*
* #var string
*/
protected $connection = 'TENANT001';
protected $table='templates';
}
After that in your config/database.php
'connections' => [
'others' => ['...']
'TENANT001' => [
'driver' => 'mysql',
'database' => env('TENANT001_DATABASE', ''),
'host' => env('TENANT001_HOSTNAME', ''),
'port' => env('DB_PORT', '3306'),
'username' => env('TENANT001_USERNAME', 'forge'),
'password' => env('TENANT001_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
Or you can use connection in the queue.php
'database' => [
'connection' => 'TENANT001'
'driver' => 'mysql',
'table' => 'jobs',
'queue' => 'default',
'expire' => 60,
],
And clear the cache once you update .env files.
php artisan config:cache
And check you have define everything correctly in .env and table exists.
Thanks
I am working on a new application that must connect to several databases. The databases are dynamically created when a new company is registered in my application i.e each company have there on databases.
My question is how to establish the database connection using laravel,
If the company admin is login he needs to connect the corresponding db. How is it possible ???
I know how to establish multiple database connection if the databases are stable, like,
'mysql1' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge1'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
...
'mysql2' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge2'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
...
but if the databases are not stable how is it possible ????
If my question is not up to standard, please forgive me
You can add dynamically the database configuration like this.
if(NULL === config()->get('database.connections.company')){
config()->set('database.connections.company', [
'driver' => $companyDbDriver,
'host' => $companyDbHost,
'port' => $companyDbPort,
'database' => $companyDbName,
'username' => $companyDbUser,
'password' => $companyDbPassword,
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false
]);
}
in the model; set the connection attribute to 'company'
/**
* Connection configuration ID.
*
* #var string
*/
protected $connection = 'company';
there are complication if you dont load the configuration of the database before calling the models using it, i'll leave that to you.
First you have to know where your database connections parameters are stored.
Anyway, wherever they are, you should create a new connection on the fly.
Supposing each User has it's own connection ...
<?php
use Illuminate\Support\Facades\Config;
$user = Users::find($id);
Config::set('database.connections.' . $user->username, array(
'driver' => 'mysql',
'host' => $user->db_host,
'database' => $user->db_name,
'username' => $user->db_user,
'password' => $user->db_pass,
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
'prefix' => '',
));
// And set the new connection to interested models
$myModel = new MyModel;
$myModel->setConnection($user->username);
$data = $myModel->where(...)->get();
Hope this help
Hello I've in config/database.php a prefix (mysql) like this:
'prefix' => 'myprefix_',
But I need, only for one model, to use a different prefix like:
protected $table = 'otherprefix_mytable';
In this way laravel looking for "myprefix_otherprefix_mytable".
Any help?
In your app/config/database.php make 2 different connections like
'connections' => array(
# first prefix
'mysql1' => array(
'driver' => 'mysql',
'host' => 'host1',
'database' => 'database1',
'username' => 'user1',
'password' => 'pass1'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => 'prefix1',
),
# second prefix
'mysql2' => array(
'driver' => 'mysql',
'host' => 'host1',
'database' => 'database1',
'username' => 'user1',
'password' => 'pass1'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => 'prefix2',
),
),
And then later in model you can use different connection
class SomeModel extends Eloquent {
protected $connection = 'mysql2';
}
For more help check this
Default table prefix can be overriding in laravel model as following example:
use Illuminate\Support\Facades\Config;
public function __construct(array $attributes = array()) {
$collection = Config::get('database');
$collection['connections']['mysql']['prefix'] = 'consultancy_';
Config::set('database',$collection);
parent::__construct($attributes);
}
Do i need to create multiple connection to access different database/schema. Cant I use with one dbconnection. Is there a way to pass the database name in the laravel eloquent or db builder? Currently in raw php i use one connection to query the different schema.
Create different connections to your database.php file and then pass them to your eloquent models.
'mysql1' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => 'db1',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
// connection 2
'mysql2' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => 'db2',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
Suppose i have model User.php uses mysql connection named mysql1
inside my model i will add :
protected $connection = 'mysql1';
if i want to use mysql connection named mysql2
then i will use
protected $connection = 'mysql2';
Here i am setting connections statically in to models.
In Eloquent, I use DB:connection() to set my named connection, like so:
$query = DB::connection('db_connection_name')->table($this->table)
If you weren't aware, the database connections are named in the config app/config/database.php
A chunk of my SQL is held in a different database to the rest of my Laravel installation.
When I use a particular Model, how do I define in that Model, that I'd like to use a particular database and not the one defined in config/database.php?
I am using Laravel 5 so needs to be relevant to that version.
Update: Here is my model;
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Lookup extends Model {
protected $connection = 'postcodes';
}
Here is part of my config/database.php;
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', $_ENV["DB_HOST"]),
'database' => env('DB_DATABASE', $_ENV["DB_DATABASE"]),
'username' => env('DB_USERNAME', $_ENV["DB_USERNAME"]),
'password' => env('DB_PASSWORD', $_ENV["DB_PASSWORD"]),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
'postcodes' => [
'driver' => 'mysql',
'host' => env('DB_HOST', $_ENV["DB_HOST"]),
'database' => env('DB_DATABASE', 'postcodes'),
'username' => env('DB_USERNAME', $_ENV["DB_USERNAME"]),
'password' => env('DB_PASSWORD', $_ENV["DB_PASSWORD"]),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
It's not working - and I can't get Whooops errors to work so all I get is a white screen (but that's a separate issue).
I know my controller code is correct because when I temporarily copy the table in to my main Laravel database, it all works fine. So what's the issue?
You can define protected $connection = 'yourohterconnection'; in your model, and add another connection to your database config file.
I asked the same question on the Laravel forum and the posted solution worked for me.
Basically the problem is this line;
'database' => env('DB_DATABASE', $_ENV["DB_DATABASE_TWO"]),
Or in my code above at the time of writing it was actually;
'database' => env('DB_DATABASE', 'postcodes'),
It needs to be;
'database' => env('DB_DATABASE_TWO', $_ENV["DB_DATABASE_TWO"]),
And then your .env file needs to have DB_DATABASE_TWO=postcodes (or whatever the name of your second database is).