How can I add another database in my laravel project in heroku - mysql

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.

Related

Copy values from one database to another using laravel

I'm using two different databases, one called "example" and another "example_hist". I'm trying to create a cron job that verifies the database "example" in table "users" if there is any user that has a state "disabled".
If there is, it should copy the user row to the table "users" inside the database "example_hist"
My problem is that I can't figure out how I can do this.
I already did the connection:
'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',
'url' => env('DATABASE_URL'),
'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' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
in my .env I have:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=example
DB_USERNAME=root
DB_PASSWORD=pass
DB_HOST_2=127.0.0.1
DB_PORT_2=3306
DB_DATABASE_2=example_hist
DB_USERNAME_2=root
DB_PASSWORD_2=pass
I already inserted the command in the kernel and this is the code I have now:
public function handle()
{
$users = DB::table('users')->where('state', 'Disabled')->get();
$user_hist = DB::connection('mysql2')->select('users');
//should be something here that copies the row from $users
}
Create one more field as copied which will be default false, and it will be true once its copied to other database
Run query whose state is disabled and not copied
$users = DB::table('users')->where('state', 'Disabled')
->where("copied", "=", 0)->get();
Run users loop
foreach ($users as $user){
//Now using connection insert into another table of another db
DB::connection('mysql2')->insert('insert into users (name, email, mobile, password, created_at, state) values (?,?,?,?,?,?)', array($user->name , $user->email , $user->mobile, $user->password, $user->created_at, $user->state ) );
//Make user copied status to true so next time it wont copied again
$user->copied = true;
$user->save();
}
Well, with the help of #Teekay I could manage to find myself the right solution. This worked for me. Hope this can help anyone with the same problem.
public function handle()
{
$users = DB::table('users')->where('state', 'Disabled')->where("copied",'false')->get();
if($users){
foreach ($users as $user){
DB::connection('mysql2')->insert('insert into users (name, email, mobile, password, created_at, state) values (?,?,?,?,?,?)', array($user->name , $user->email , $user->mobile, $user->password, $user->created_at, $user->state ) );
DB::table('users')->where('state', 'Disabled')->where("copied", 'false')->update(['copied' => 'true']);
}
}
}

Migration of tables to database

screenshot of Error i am getting>Illuminate\Database\QueryException SQLSTATE[HY000] [1049] Unknown database 'hiring' (SQL: insert into hirings (name, email, subject, message, updated_at, created_at) values (, , , , 2018-01-24 19:31:19, 2018-01-24 19:31:19))
Portfolio is my database name
In .env file is the same, my model name is hiring, my table name is create_hiring_table everything looks fine to me. Anything I am missing?
.env
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:9ALfdXT6SdgOkZ3gFVCExTFY4z/8yzOfbuCuB7dA1h0=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=portfolio
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=sync
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
my model name hiring.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
class hiring extends Model
{
use Notifiable;
protected $fillable = [
'name','email','subject','message'
];
protected $hidden = [
'password', 'remember_token',
];
}
my controller named mainController
<?php
namespace App\Http\Controllers;
use App\hiring;
use Illuminate\Http\Request;
class mainController extends Controller
{
public function index(){
return view('main.main');
}
public function store(Request $request){
$hiring = new hiring;
$hiring-> name = $request->name;
$hiring-> email = $request->email;
$hiring-> subject = $request->subject;
$hiring-> message = $request->message;
$hiring-> save();
return view('main.main');
}
}
My table is following named create_hiring_table
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateHiringsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('hiring', function (Blueprint $table){
$table->increments('id');
$table->timestamps();
$table->string('name');
$table->string('email');
$table->string('subject');
$table->string('message');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('hiring');
}
}
This is config/databse.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' => env('DB_SOCKET', ''),
'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,
],
],
];
just add protected $table = 'hiring';
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
class hiring extends Model
{
use Notifiable;
protected $table = 'hiring';
protected $fillable = [
'name','email','subject','message'
];
protected $hidden = [
'password', 'remember_token',
];
}
i found the mistake ever in web.php the rout should be Route::post('/main', 'mainController#store'); instead of Route::get('/main', 'mainController#store');

How i can force an yii2 module to use a specific connection for all his models?

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();

Laravel 4 artisan migrate install

I'm trying to migrate a very basic app from Laravel 3 to Laravel 4. It looks very easy but for some reason the following command is not working.
php artisan migrate:install
Following this tutorial: http://laravel.com/docs/quick#installation it seems like we don't need to install the artisan anymore. So I tried just running
php artisan migrate
But I always get the error
[ErrorException]
Undefined index: collation
My database.php:
'fetch' => PDO::FETCH_CLASS,
'default' => 'mysql',
'connections' => array(
'sqlite' => array(
'driver' => 'sqlite',
'database' => __DIR__.'/../database/production.sqlite',
'prefix' => '',
),
'mysql' => array(
'driver' => 'mysql',
'host' => '127.0.0.1',
'database' => 'wepromoters_db',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'prefix' => '',
),
'pgsql' => array(
'driver' => 'pgsql',
'host' => 'localhost',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
),
'sqlsrv' => array(
'driver' => 'sqlsrv',
'host' => 'localhost',
'database' => 'database',
'username' => 'root',
'password' => '',
'prefix' => '',
),
),
'redis' => array(
'cluster' => true,
'default' => array(
'host' => '127.0.0.1',
'port' => 6379,
'database' => 0,
),
),
My migration:
public function up()
{
Schema::create('users',function($table){
$table->increments('id');
$table->string('email')->unique();
$table->string('password');
$table->string('type');
$table->timestamps();
});
}
Lastly the db is working fine with my Laravel 3 app
What is going on?
According to this thread on the Laravel forums, a collation parameter is now required in the database configuration.
Try it with this (notice the extra "collation" parameter after the "charset" one) :
'mysql' => array(
'driver' => 'mysql',
'host' => '127.0.0.1',
'database' => 'wepromoters_db',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
Laravel 4 is entirely different with Laravel 3, So use laravel 4 commands to migrate your table. I don't know exactly but you can try with this command:
php artisan make:migration create_users_table(Enter)
So, we created default users table and have to create our table:
php artisan make:migration create_YourTableName_table -- create YourTableName
Then, check your file in "migration/YourTableName.php" by opening it.
Now, you can write your code under the "Run Migration Block".
Finally, Run this command to migrate your table.
php artisan migrate
It will migrate your table with in span of time.

two databases in one controller cakePHP

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' => ''
);
}