Laravel seed database from existing database - mysql

i have now new structure of my database, but i need to import the old data in the new format. For that reason i want to use the Laravel seeder, but i need somehow to connect to the old database and make select queries and to tell the seeder how to put the data in the new database.
Is that possible ?

Try:
Examples:
php artisan iseed my_table
php artisan iseed my_table,another_table
Visit: https://github.com/orangehill/iseed

Configure your laravel app to use two mysql connections (How to use multiple database in Laravel), one for the new database, the other for the old one.
I'll fake it like old and new.
In your seeds read from the old database and write into the new.
$old_user = DB::connection('old')->table('users')->get();
foreach ($old_users as $user) {
DB::connection('new')->table('users')->insert([
'name' => $user->name,
'email' => $user->email,
'password' => $user->password,
'old_id' -> $user->id
// ...
]);
}
Make sure to add messages while seeding like $this->command->info('Users table seeded'); or even a progress bar (you can access command line methods) to know at which point of the import you are.

Download package from
Git repo : https://github.com/orangehill/iseed
then update below file src/Orangehill/Iseed/IseedCommand.php
Add below code at line number 75
// update package script
if($this->argument('tables') === null){
$tables = Schema::getConnection()->getDoctrineSchemaManager()->listTableNames();
}
and update getArguments method in same file with below code
array('tables', InputArgument::OPTIONAL, 'comma separated string of table names'),
and then run php artisan iseed so it will get all the tables from your existing db and start creating seeders for all tables

Related

Doctrine 2.5 - Generate schema provider class from existing database

Question
Are there any existing tools able to generate an implementation of Doctrine\DBAL\Migrations\Provider\SchemaProvider reflecting the state of an existing database?
I googled for a while and looked at similar questions in SO but i couldn't find an answer. They are all related to Symfony + Doctrine ORM.
Why do i need this?
I want to use doctrine migrations to manage/track changes on an existing database. I cannot jump into using doctrine ORM because I would need to refactor the database and it would break other ( non php ) applications that depend on it.
I know i can use migrations without ORM, but i need to provide a concrete implementation of Doctrine\DBAL\Migrations\Provider\SchemaProvider (documentation), in my case this would mean to rewrite the entire database.
If i had the SchemaProvider generated for the first time to reflect the state of the database. Eg
<?php
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Migrations\Provider\StubSchemaProvider;
final class MySchemaProvider implements SchemaProvider {
public function createSchema()
{
$schema = new Schema();
$table = $schema->createTable('foo');
$table->addColumn('id', 'integer', array(
'autoincrement' => true,
));
$table->setPrimaryKey(array('id'));
//and so on for the rest of the databse...
return $schema;
}
}
I would be able to edit the generated class and create migrations with:
$ ./doctrine migrations:diff

database error after adding new column

I had created a login and register form. But I forgot to add a column. So, I wanted to add a new column named "contactNumber". For adding the column, I wrote a command named php artisan migrate:refresh in cmd.exe and also write a code at create_users_table in migration folder. But, the new column's value doesn't go to mysql database. What am I doing wrong?
You need to add your new column to your model, so in your User class you need to do this:
protected $fillable = [
'name', 'email', 'password', 'contactNumber'
];
Hope this help
You're trying to insert a new record in the database but the contactNumber column doesn't have a default value. In the migration file you can add nullable to that column, eg.
$table->string('contactNumber')->nullable();
or directly in the database from a GUI.
For this type of scenario i personally create new migration like this
php artisan migrate:make add_column_to_table --table="tableName"
Now to run the new migration run this command.
php artisan migrate
This will add new column in your table.Also have a look into this thread.
https://laracasts.com/discuss/channels/laravel/add-new-column-to-existing-table

Backing Up MySQL's Data

As while using Laravel, we have an option to seed our database or create tables anytime, like
class UsersTableSeeder extends Seeder
{
public function run()
{
User::truncate();
User::create([
'username' => 'Junaid',
'email' => 'darulehsan03#gmail.com',
'password' => '1234'
]);
User::create([
'username' => 'Junaid Farooq',
'email' => 'aba#bcd.com',
'password' => '4321'
]);
}
}
we can seed our database anytime, but what if we have a large no of rows in our table, which are not being seeded but added by the users , then how can we put it that way, like a Seeder file so, anytime at anyplace , we can load all those rows through our Seeder File?
not asking about to save .SQL file and then import or Export it, But a way to backup them in a Seeder file
I don't know of any method of backing up the data to a seed file. You can, like you've already said, export and import your data.
There are also a couple of packages available to backup and restore a database.
laravel-backup, which seems to be a Laravel-specific package that allows you to backup your database and restore it.
database-backup, which is framework agnostic but does come with a Laravel service provider for easier integration with Laravel.
Both seem to allow you to backup and restore from Amazon S3. Having used neither I can't say which is better or why. You'll have to try both out and make that decision for yourself.

Backup database(s) using query without using mysqldump

I'd like to dump my databases to a file.
Certain website hosts don't allow remote or command line access, so I have to do this using a series of queries.
All of the related questions say "use mysqldump" which is a great tool but I don't have command line access to this database.
I'd like CREATE and INSERT commands to be created at the same time - basically, the same performance as mysqldump. Is SELECT INTO OUTFILE the right road to travel, or is there something else I'm overlooking - or maybe it's not possible?
Use mysqldump-php a pure-PHP solution to replicate the function of the mysqldump executable for basic to med complexity use cases - I understand you may not have remote CLI and/or mysql direct access, but so long as you can execute via an HTTP request on a httpd on the host this will work:
So you should be able to just run the following purely PHP script straight from a secure-directory in /www/ and have an output file written there and grab it with a wget.
mysqldump-php - Pure PHP mysqldump on GitHub
PHP example:
<?php
require('database_connection.php');
require('mysql-dump.php')
$dumpSettings = array(
'include-tables' => array('table1', 'table2'),
'exclude-tables' => array('table3', 'table4'),
'compress' => CompressMethod::GZIP, /* CompressMethod::[GZIP, BZIP2, NONE] */
'no-data' => false,
'add-drop-table' => false,
'single-transaction' => true,
'lock-tables' => false,
'add-locks' => true,
'extended-insert' => true
);
$dump = new MySQLDump('database','database_user','database_pass','localhost', $dumpSettings);
$dump->start('forum_dump.sql.gz');
?>
With your hands tied by your host, you may have to take a rather extreme approach. Using any scripting option your host provides, you can achieve this with just a little difficulty. You can create a secure web page or strait text dump link known only to you and sufficiently secured to prevent all unauthorized access. The script to build the page/text contents could be written to follow these steps:
For each database you want to back up:
Step 1: Run SHOW TABLES.
Step 2: For each table name returned by the above query, run SHOW CREATE TABLE to get the create statement that you could run on another server to recreate the table and output the results to the web page. You may have to prepend "DROP TABLE X IF EXISTS;" before each create statement generated by the results of these queryies (!not in your query input!).
Step 3: For each table name returned from step 1 again, run a SELECT * query and capture full results. You will need to apply a bulk transformation to this query result before outputing to screen to convert each line into an INSERT INTO tblX statement and output the final transformed results to the web page/text file download.
The final web page/text download would have an output of all create statements with "drop table if exists" safeguards, and insert statements. Save the output to your own machine as a ".sql" file, and execute on any backup host as needed.
I'm sorry you have to go through with this. Note that preserving mysql user accounts that you need is something else entirely.
Use / Install PhpMySQLAdmin on your web server and click export. Many web hosts already offer you this as a service pre-configured, and it's easy to install if you don't already have it (pure php): http://www.phpmyadmin.net/
This allows you to export your database(s), as well as perform other otherwise tedious database operations very quickly and easily -- and it works for older versions of PHP < 5.3 (unlike the Mysqldump.php offered as another answer here).
I am aware that the question states 'using query' but I believe the point here is that any means necessary is sought when shell access is not available -- that is how I landed on this page, and PhpMyAdmin saved me!

Cakephp - Connect to different database/host from inside an action

In cakephp I want to be able connect to a different database from one action on the site. The action determines which database and host to connect to. Using cakephp 1.3.
Ive seen where you can change the db connection in beforeFilter for a controller, but I want to be able handle this from the action, because that is where I find the database and/or host, that I need to connect to.
I can write my own SQL inside there. I don't need to go through models. Just want to do a simple add/update SQL statement.
You can easily configure more than one database connection to use in your app.
In config/database.php, create another variable for your database configuration, in addition to the existing $default:
var $otherDatabase = array(
'driver' => 'mysql',
// more settings...
);
Then, in your model, set $this->useDbConfig = 'otherDatabase' or in your controller $this->MyModel->useDbConfig = 'otherDatabase'. Any subsequent find()s will use the configured database.