How can drop colum in table - php

Is this query is correct?
I'm using Laravel 8, and I want to drop a column in a table. But this query isn't working.
php artisan make:migration remove_contact_no_from_customer --table=customer

you should use To drop a column, you may use the dropColumn method on the schema builder blueprint:
first, you can create a migration file:
php artisan make:migration remove_contact_no_from_customer --table=customer
then, in that migration, make sure you code will be:
Schema::table('customer', function (Blueprint $table) {
$table->dropColumn('contact_no');
});

To drop a table in laravel, Create a first migration
Step to drop a table
$ php artisan make:migration drop_user_table
Add this to your migrate file inside up function Schema::drop('tableName');
public function up()
{
Schema::dropIfExists(table('songs'));
$table->increments('id');
...
}
then run
$ php artisan migrate

That's not a query. It only creates a migration file in your database/migrations folder where you have to add some code like so:
public function up() {
Schema::table('customer', function (Blueprint $table) {
$table->dropColumn('contact_no');
});
}
Afterward, just run php artisan migrate to apply your new migrations to the database, which will drop this column.

Related

laravel, update table structure but get error table already exist when use php artisan migrate

I have table and I wanted to update on some columns, or if I wanted to add new column the problem is when I want to use php artisan migrate command gives me error table already exist, also Im using depoly file and the command inside it is php artisan migrate --force so hope this is correct or have to add any more command??
public function up()
{
Schema::create('payment_methods', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->unsigned();
$table->string('paymentreference')->unique();
$table->string('payment_token');
$table->string('cardnumber'); //updated
$table->string('cardbin')->nullable();
$table->string('cardlast4');
$table->string('cardtype');
$table->string('expirymonth');
$table->string('expiryyear');
$table->string('cardholdername'); //added
$table->timestamps();
});
}
To added new or update field like profile in payment_methods.
Try
Run command:
php artisan make:migration add_profile_to_payment_methods
And in the up() method of the new migration file generated, use Schema::table() method to add the new columns or modifying the table.
public function up()
{
Schema::table('payment_methods', function (Blueprint $table) {
$table->string('profile')->nullable();
});
}
public function down()
{
Schema::table('payment_methods', function (Blueprint $table) {
$table->dropColumn('profile');
});
}
}
Then run migration to update the table using php artisan migrate
You need a new migration to modify existing table.
Create new migration:
php artisan make:migration modify_payment_methods_table
Then open the migration file and put following code in there:
public function up()
{
Schema::table('payment_methods', function (Blueprint $table) {
$table->string('cardnumber')->change();
$table->string('cardholdername');
});
}
public function down()
{
Schema::table('payment_methods', function (Blueprint $table) {
$table->integer('cardnumber')->change(); // todo: if this was not an integer then fix this to be correct type instead of integer to avoid issue in case if you will have to rollback the migration
$table->dropColumn('cardholdername');
});
}
After this run
php artisan migrate
To do this successfully you may need to install additional dependency doctrine/dbal.
You can install that easily with composer:
composer require doctrine/dbal
You have manipulated or an error has occurred in any of the migrations.
Well, now in the migrations table, there isn't a row that contains create_payment_methods_table in the migrations column.
As it does not exist, but the table to which the migration refers, if it exists in your database, it fails you, since the process is as follows:
When you refresh, Laravel reads the migrations table, and executes
each migration file in order, first executing the down or deletion of
the table.
After executing that step in all migrations, go through the UP. When
the down of that table does not exist, when arriving at its demo
file, the up finds that it already exists. And that's why it fails
you.,
The solution is to delete manually the referenced table and rerun the migration

Laravel 5 - Use migrate:rollback with path

I've inserted a column with name im_useless to my table earlier which I do not need anymore.
This is my schema (filename: 2017_02_27_120313_units.php):
public function up()
{
Schema::create('units', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('description');
$table->string('im_useless');
$table->timestamps();
});
}
Now I try to remove it, so I used this code inside the down() function:
public function down()
{
Schema::dropColumn('im_useless');
}
New Schema:
public function up()
{
Schema::create('units', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('description');
$table->timestamps();
});
}
Now I have to rollback and then migrate again. I try to rollback only that specific migration file, by executing php artisan help migrate:rollback I found out that there is a --path option.
So I tried to rollback that specific migration like this:
php artisan migrate:rollback --path=2017_02_27_120313_units.php
But I get Nothing to rollback
How can I drop that specific column without having to rollback any other migrations?
UPDATE:
I think I have to change the path like this:
php artisan migrate:rollback --path=database/migrations/2017_02_27_120313_units.php
...since my php shell was opened in the project root folder?
However I still get Nothing to rollback
I also tried php artisan migrate --path=2017_02_27_120313_units.php
and php artisan migrate --path=database/migrate/2017_02_27_120313_units.php
...and get Nothing to migrate
UPDATE 2
I think I have messed up my migrations table, because I removed the code inside the down() function and the table was never deleted.
https://stackoverflow.com/a/26077506/4684797
The rollback function is meant to give you the possibility to revert to the version you had right before you migrated, in case something goes wrong when you deploy. If you want to drop a specific column that you don't need anymore, you should treat that as a new migration and drop the column in the up() method.
If your laravel version is >= 5.3 you could simply add the migrations path like packages does.
https://laravel.com/docs/5.3/packages#migrations
Just put this code in your AppServiceProvider boot method:
$this->loadMigrationsFrom(__DIR__.'/path/to/migrations');
Also if you want to include subfolders recursively you can try with "/path/to/migrations/**/*" but I'm not sure if this will work in older laravel versions.
--path param is like a filter. It will work on the latest migrations that rollback will act. You can use path reference starting from datatabase/migrations. For example:
php artisan migrate:rollback --path=database/migrations/2022_10_03_193316_create_something.php
It will work if in your database, you have something like 2022_10_03_193316_create_something.php on migration column plus greatest batch value.
Tested on Laravel 6
Run composer dump-autoload and try again

Laravel migrate:rollback adding and deleting table columns

I have used the php artisan migrate:make add_something_to_to_user_table --table=users
and coded
Schema::table('users', function(Blueprint $table)
{
$table->string('description1');
$table->string('description2');
$table->string('description3');
});
and added three fields and gave php artisan migrate and the fields got stored in to the database
also found that the migration table is updated with the row 2014_11_05_145536_add_something_to_to_user_table
now when i use php artisan migrate:rollback
The 2014_11_05_145536_add_something_to_to_user_table row in the migration table is missing but the columns added to the users table remains the same
why it is not deleting the fields in the table also which results in error while using php artisan migrate again...
You should have a down() method in you migration that should look like this:
public function down()
{
Schema::table('users', function($table)
{
$table->dropColumn(array('description1', 'description2', 'description3'));
});
}
That will be called on rollback and will take care of removing the columns added by the migration.
According to laravel 7+ doc this will also work when you need to drop multiple columns at the same time.
public function down(){
Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['description1', 'description2', 'description3']);
});
}
Add down public function to drop users table when rollback..
public function down()
{
Schema::drop('users');
}

Can I create database tables automatically in Laravel like Django's 'python manage syncdb'?

I came from Django(Python) background and these days I'm working on a project which is based on Laravel(PHP).Do I have some option like generating database tables automatically?
Yes, using the Schema Builder and Migrations.
First you need to install the migrations table to the DB:
$ php artisan migrate:install
then create a migration
$ php artisan migrate:make create_users_table
this will create a PHP file in application/migrations. You may now edit it to have the settings you want, i.e.
<?php
class Create_Users_Table
{
public function up()
{
Schema::create('users', function($table)
{
$table->increments('id');
$table->string('username');
$table->string('email');
$table->string('phone')->nullable();
$table->text('about');
$table->timestamps();
});
}
public function down()
{
Schema::drop('users');
}
}
and execute it using
$ php artisan migrate
Every time you change the database structure you'll have to create a new migration and execute it afterwards.
Say you want users to have a new column hometown instead of phone you'd create a new migration
$ php artistan migrate:make users_table_add_hometown
and edit the new file to contain
<?php
class Users_Table_Add_Hometown
{
public function up()
{
Schema::table('users', function($table)
{
$table->string('hometown');
$table->drop_column('phone');
});
}
public function down()
{
Schema::table('users', function($table)
{
$table->string('phone')->nullable();
$table->drop_column('hometown');
});
}
}
You now have two migrations, one creating the table and one modifying it.
The artisan migrate command is smart enough to only execute migrations that are new to the system. So if a collegue of yours comes home after a long vacation and there were a few new migrations it will automatically only import the ones that were created after he left.

Laravel Add a new column to existing table in a migration

I can't figure out how to add a new column to my existing database table using the Laravel framework.
I tried to edit the migration file using...
<?php
public function up()
{
Schema::create('users', function ($table) {
$table->integer("paid");
});
}
In terminal, I execute php artisan migrate:install and migrate.
How do I add new columns?
To create a migration, you may use the migrate:make command on the Artisan CLI. Use a specific name to avoid clashing with existing models
for Laravel 5+:
php artisan make:migration add_paid_to_users_table --table=users
for Laravel 3:
php artisan migrate:make add_paid_to_users
You then need to use the Schema::table() method (as you're accessing an existing table, not creating a new one). And you can add a column like this:
public function up()
{
Schema::table('users', function($table) {
$table->integer('paid');
});
}
and don't forget to add the rollback option:
public function down()
{
Schema::table('users', function($table) {
$table->dropColumn('paid');
});
}
Then you can run your migrations:
php artisan migrate
This is all well covered in the documentation for both Laravel 4 / Laravel 5:
Schema Builder
Migrations
And for Laravel 3:
Schema Builder
Migrations
Edit:
use $table->integer('paid')->after('whichever_column'); to add this field after specific column.
I'll add on to mike3875's answer for future readers using Laravel 5.1 and onward.
To make things quicker, you can use the flag "--table" like this:
php artisan make:migration add_paid_to_users --table="users"
This will add the up and down method content automatically:
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
//
});
}
Similarily, you can use the --create["table_name"] option when creating new migrations which will add more boilerplate to your migrations. Small point, but helpful when doing loads of them!
In case you want to add new column as a FOREIGN KEY to an existing table.
Create a new migration by executing this command : make:migration
Example :
php artisan make:migration add_store_id_to_users_table --table=users
In database/migrations folder you have new migration file, something like :
2018_08_08_093431_add_store_id_to_users_table.php (see the comments)
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddStoreIdToUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
// 1. Create new column
// You probably want to make the new column nullable
$table->integer('store_id')->unsigned()->nullable()->after('password');
// 2. Create foreign key constraints
$table->foreign('store_id')->references('id')->on('stores')->onDelete('SET NULL');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
// 1. Drop foreign key constraints
$table->dropForeign(['store_id']);
// 2. Drop the column
$table->dropColumn('store_id');
});
}
}
After that run the command :
php artisan migrate
In case you want to undo the last migration for any reason, run this command :
php artisan migrate:rollback
You can find more information about migrations in the docs
If you're using Laravel 5, the command would be;
php artisan make:migration add_paid_to_users
All of the commands for making things (controllers, models, migrations etc) have been moved under the make: command.
php artisan migrate is still the same though.
In Laravel 8
php artisan make:migration add_columnname_to_tablename_table --table=tablename
then after creating migration in
public function up()
{
Schema::table('users', function (Blueprint $table) {
// 1. Create new column
$table->datatype('column_name')->nullable();
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
// 1. Create new column
$table->dropColumn('column_name');
});
}
then run
php artisan migrate
if you face error then rename the migration name with the date before the table created and then run again php artisan migrate
You can add new columns within the initial Schema::create method like this:
Schema::create('users', function($table) {
$table->integer("paied");
$table->string("title");
$table->text("description");
$table->timestamps();
});
If you have already created a table you can add additional columns to that table by creating a new migration and using the Schema::table method:
Schema::table('users', function($table) {
$table->string("title");
$table->text("description");
$table->timestamps();
});
The documentation is fairly thorough about this, and hasn't changed too much from version 3 to version 4.
Laravel 7
Create a migration file using cli command:
php artisan make:migration add_paid_to_users_table --table=users
A file will be created in the migrations folder, open it in an editor.
Add to the function up():
Schema::table('users', function (Blueprint $table) {
// Create new column
// You probably want to make the new column nullable
$table->integer('paid')->nullable()->after('status');
}
Add to the function down(), this will run in case migration fails for some reasons:
$table->dropColumn('paid');
Run migration using cli command:
php artisan migrate
In case you want to add a column to the table to create a foreign key constraint:
In step 3 of the above process, you'll use the following code:
$table->bigInteger('address_id')->unsigned()->nullable()->after('tel_number');
$table->foreign('address_id')->references('id')->on('addresses')->onDelete('SET NULL');
In step 4 of the above process, you'll use the following code:
// 1. Drop foreign key constraints
$table->dropForeign(['address_id']);
// 2. Drop the column
$table->dropColumn('address_id');
this things is worked on laravel 5.1.
first, on your terminal execute this code
php artisan make:migration add_paid_to_users --table=users
after that go to your project directory and expand directory database - migration and edit file add_paid_to_users.php, add this code
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('paid'); //just add this line
});
}
after that go back to your terminal and execute this command
php artisan migrate
hope this help.
First rollback your previous migration
php artisan migrate:rollback
After that, you can modify your existing migration file (add new , rename or delete columns) then Re-Run your migration file
php artisan migrate
WARNING: this is a destructive action. If you use this ensure you back up your database first.
You can simply modify your existing migration file, for example adding a column in your table, and then in your terminal typing :
$ php artisan migrate:refresh
Add column to your migration file and run this command.
php artisan migrate:refresh --path=/database/migrations/your_file_name.php
STEP 1
php artisan make:migration add_sex_to_users_table --table=users
STEP 2
In the newly generated migration file, you will find up and down hook methods. in up hook, add there columns that you want to add, and in down hook, add there columns that you need to remove. for example, Me i need to add sex on column of users, so I will add there following line in the up hook.
$table->integer('quantity')->default(1)->nullable();
So I have something like this
public function up()
{
Schema::table('service_subscriptions', function (Blueprint $table) {
$table->integer('quantity')->default(1)->nullable();
});
}
STEP 3
Run the migration command as follows
php artisan migrate
Then you will have a new column added
In laravel 8
php artisan make:migration add_paid_to_users_table --table=users
public function up()
{
Schema::table('users', function($table) {
$table->integer('paid');
});
}
In laravel 9
add a new column in existing table
php artisan make:migration add_paid_to_users_table
if you want to create new migration then do the below code
php artisan make:migration create_users_table --create=users
First you have to create a migration, you can use the migrate:make command on the laravel artisan CLI.Old laravel version like laravel 4 you may use this command
for Laravel 4:
php artisan migrate:make add_paid_to_users
And for laravel 5 version
for Laravel 5+:
php artisan make:migration add_paid_to_users_table --table=users
Then you need to use the Schema::table() . And you have to add the column:
public function up()
{
Schema::table('users', function($table) {
$table->integer('paid');
});
}
If you don't want to split the blueprint(schema) into two migration file then the best thing you can do is drop the table from the database and then rename the migration file's last number and do
php artisan migrate
This helps you to protect the data of other tables.
Run this command:
php artisan migrate:fresh --seed
it will drop the table and re add it updating all the columns adding to the database
What you can do is Like,
Schema::create('users', function ($table) { $table->integer("paid"); });
After Writing this write command php artisan migrate or php artisan refresh
What i personally prefer is to refresh rather than fresh migration because if you do fresh migrate it will remove all the data refresh will not.
but only exception is if you do refresh and if you have any foreign key in table so it will not going to re-establish the relationship so you will get error like,
Cannot add foreign key constrain
If none of the solve worked, you might have recreated the migration file then added a new column and tried to run php artisan migrate to update the old table which will try to create that table but the table already exists so it gives an error. To solve that rename the migration file as previously named (started with a date), then add new column run php artisan migrate that will actually update the old one instead of create, solved my problem.
Although a migration file is best practice as others have mentioned, in a pinch you can also add a column with tinker.
$ php artisan tinker
Here's an example one-liner for the terminal:
Schema::table('users', function(\Illuminate\Database\Schema\Blueprint $table){ $table->integer('paid'); })
(Here it is formatted for readability)
Schema::table('users', function(\Illuminate\Database\Schema\Blueprint $table){
$table->integer('paid');
});

Categories