Laravel Migrations insert into table - php

In Laravel 5.3 within my up() function how can I insert data into another table?
I can only see things in the guide for updating columns etc

You can do it as what you do in normal Laravel code as long as that table has been created already. For example:
public function up()
{
Schema::create('this_table', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
\DB::table('that_table')->insert([]);
}
As others suggest, you should consider if it's better to move such logic into database seeders. However, I find sometimes it's better to have such logic just live inside migration files when your table have constant initial data.
FYI, Here is an open source Laravel project does this.
===========Edit 5 years later=============
I suggest anyone want to do this consider database seeders as the original answer suggested. Now Laravel have a schema:dump command that can be used for squashing your migrations. This might be useful if you have a project with many migrations. For me, I have a project with 408 migrations and it's not easy to use the schema:dump now as data filling methods in migrations will be lost.

You can insert to the table as shown below after the table is created.
DB::table('tablename')->insert([
['columnname1' => 1, 'columnname2' => 'Girl'],
['columnname1' => 2, 'columnname2' => 'Boy']
]);

Related

Laravel: Add column to table with updated migration

I'm trying to migrate a specific line in one migration file.
Example:
Before:
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('category_name');
$table->integer('parent_id')->nullable();
$table->timestamps();
});
After:
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('category_name');
$table->string('img_url'); // ← new column
$table->integer('parent_id')->nullable();
$table->timestamps();
});
And now I just want to migrate the line: $table->string('img_url');
Is it possible?
It sounds like you are trying to add a column to a table that has already been created via migration. If that is the case, rather than using Schema::create(...), you need to use Schema::table(...).
Typically, you would create a new migration for this:
$ php artisan make:migration add_img_url_to_categories
Which will create a new file at /database/migrations called something like 2019_10_21_165554_add_img_url_to_categories.php. Then add this code to the up() function:
public function up()
{
Schema::table('categories', function (Blueprint $table) {
$table->string('img_url');
});
}
Another option you have is to edit the migration exactly as you have done (per the code in your question), and then run:
$ php artisan migrate:fresh // drop all tables and re-run all migrations
or
$ php artisan migrate:refresh // reset and re-run all migrations
But keep in mind that these are both destructive operations – meaning you will lose any data you already have in your database. In early development, that might not matter. But you should really establish the habit of creating new migrations for database changes, rather than editing existing migrations.
The purpose of migrations is so that you (or anyone using your app) can quickly deploy a database that matches the schema your app is expecting.
During development, it is not uncommon to edit your migrations as you tweak your database schema to accommodate the features you are developing.
However, once you have deployed or published your app, you should consider all of the migrations to be locked or read-only. Any database changes from that point should be done in a new migration.

I can’t add new columns to the table from laravel even after following the procedure of migration?

I am following all the steps for adding new column votes to the user table from laravel, still there isn't in the database? Please tell me where is my mistake?
Firstly
php artisan make:migration add_votes_to_users_table --table=users
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->integer('votes');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('votes');
});
}
php artisan migrate
enter image description here
Error from cmd-
In Connection.php line 647:
SQLSTATE[42S01]
And
In Connection.php line 449:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' already
exists
I am suspecting that the reason you are getting this errors can come from 2 sides.
1) you created users table yourself without run any migration
2) a migration was interrupted.
If the above does not work try:
php artisan migrate:reset
to rollback all your changes or if you want to move back 1 step at a time you can try:
php artisan migrate:rollback --step=1
Last if you are sure you can start over and you are ok with that you can run:
php artisan migrate:fresh
This will drop all the tables (check the database just to be sure as well and drop yourself any remaining even though i don't think anything will be left, never happened to me) and then run
php artisan migrate
all over again
Check your data base. the users table already exit or not. if you create manually. you get this type of error. if users table ther you can remove manually from data base.
Thanks all of you for your suggestions, Sasa Blagojevic you are right about one thing my database was created in wrong way. Actually main problem arise when I created the database first time that time SQLSTATE[42000] appeared for user table. That why when updating the table previous error was still showing. After solving it there wasn't error now.

Run artisan in Laravel code without creating migration records in the table migrations

I have this code in my function to run all migrations files in a folder to create new tables in a new database on the fly. However, every time I run it, it creates a new record in the table migration which is normal. But the next time I run the function again, the migration files are excluded because they have been run before.
How do I force it not to write anything to the table "migrations"? because I don't want this to be a part of the deployment. Those tables are used for creating new tenant client.
Artisan::call('migrate', array('--path' => 'database/templates', '--force' => true));
After understanding your goal better, it sounds like you wish to create additional tables when an event happens.
For this you'll just need to use the Schema builder to do it and avoid using migrations altogether. Consider the following example:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
Schema::create('new_table_name', function (Blueprint $table) {
$table->increments('id');
// additional columns
$table->timestamps();
$table->softDeletes();
});
You can wrap this in a new class method to trigger when you want to create an additional table without effecting migrations.
If you wish to drop a table later you can run:
Schema::dropIfExists('new_table_name');
It looks like I can use the option --pretend to dump all the queries without writing the migration batch
Options:
...
--pretend Dump the SQL queries that would be run.
...

Creating Temporary table in laravel/lumen and insert data

I want to create temporary table in Laravel/Lumen and I made schema like this.
Schema::create('temp_image', function (Blueprint $table) {
$table->increments('id');
$table->string('link');
$table->timestamps();
$table->temporary();
});
When I run php artisan migrate I see...
Migrating: 2017_11_25_165640_create_temp_table
Migrated: 2017_11_25_165640_create_temp_table
... but it didn't create any tables. What happened?
Temporary tables are session based. It is not created on SQL Server. You can have a look in this article in laracast.
Temporary table can be used in lumen too. We can use Schema Builder
to create table and drop table.
Let assume, we have a function for a simple request. We could use temporary table like the following-
public function temporary_check()
{
Schema::create('temp_message', function (Blueprint $table) {
$table->increments('id');
$table->integer('sender_id');
$table->integer('receiver_id');
$table->string('message');
$table->timestamps();
$table->temporary();
});
DB::table('temp_message')->insert(['sender_id'=>2,'receiver_id'=>3,'message'=>'message temp check']);
$data = DB::table('temp_message')->get();
Schema::drop('temp_message');
return $data;
}
As Temporary Table are session based, you should always free-up memory by dropping tables at the end of your work.
A temporary table is a special type of table that allows you to store a temporary result set, which you can reuse several times in a single session. So, if you are trying to find them, you probably won't get it as they are session-based.
MySQL removes the temporary table automatically when the session ends or the connection is terminated.
You should keep in mind that these tables are created without indexes, so if your goal is to improve the speed of queries, adding an index after creating the table is usually desirable.
You can read more about it: http://www.mysqltutorial.org/mysql-temporary-table/

Laravel 5.2 how to update migration without losing data

I'm using laravel 5.2 and I usually update my database according to project requirements, so I'd like to do it without losing database records.
I don't mean how to seed my database.. I mean when my database is live and I want to update it throw laravel migration.
I was going throw Laravel Documentation but I found nothing, so I hope to find somebody help me
Since you already have data in your tables then instead of rolling back your migrations (which will cause existing data losses) you can create new migration files to update your tables. Suppose you have a table users with columns name, email, password. You stored data in that table. Then you realized that you also do need to add a new column named mobile_no to your users table. To do this you need to create a new migration file. Command will be:
php artisan make:migration add_mobile_no_columns_to_users_table --table=users
This way a new migration file will be created. Set your column details there, run the migrations using php artisan migrate and that's all. You'll have this new column in your users table without losing previously stored data.
Please note that when you add a new column for a table while already there are data, you have to set a default value for new column or make it nullable type.. otherwise you will endup with error
Make sure that when you are adding new column in your table, that column should be nullable, and should not be unique. Otherwise you will face error. Because when a new column is created it will be empty(not unique). In that condition you have to rollback the migration.
Make a new migration with
php artisan make:migration change_body_to_nullable_in_reviews_table --table=reviews
where you put this
public function up()
{
Schema::table('reviews', function (Blueprint $table) {
$table->text('body')->nullable()->change();
});
}
public function down()
{
Schema::table('reviews', function (Blueprint $table) {
$table->text('body')->nullable(false)->change();
});
}
And then run PHP artisan migrate

Categories