rename column in laravel using migration [duplicate] - laravel

This question already has answers here:
Laravel migrations: Class "not found"
(14 answers)
Closed 3 months ago.
I use laravel 5.6
I want to change author_ID to user_id
I have columns as mentioned below:
class CreatePostsTable extends Migration{
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->bigInteger('author_ID');
$table->text('title');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('posts');
}
}
I use the below link to change my column name :
How can I rename a column in laravel using migration?
then create blow migration :
php artisan make:migration rename_author_id_in_post_table
rename migration file :
class UpdateUsernameInPostTable extends Migration{
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->renameColumn('author_ID', 'user_id');
});
}
public function down()
{
Schema::create('posts', function (Blueprint $table) {
$table->renameColumn('user_id', 'author_ID');
});
}
}
but with the run command : php artisan migrate I have the below error :
Symfony\Component\Debug\Exception\FatalThrowableError :
Class 'RenameAuthorIdInPostTable' not found

Just try this code after deleting your existing migration for updating name,
php artisan make:migration rename_author_id_in_posts_table --table=posts
It will create one migration and then replace up() and down() functions with this in that created migration,
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->renameColumn('author_ID', 'user_id');
});
}
And down() function with this,
public function down()
{
Schema::table('posts', function (Blueprint $table) {
$table->renameColumn('user_id', 'author_ID');
});
}
For more information about migration, you can go through this link Laravel Migrations.
PROBLEM WITH YOUR MIGRATION:
You are using Schema::create() method for change in table, As you have already created migration for posts table,You don't need to do Schema::create() just use Schema::table() method to update and change in any fields.
Schema::create('posts', function (Blueprint $table) {
$table->renameColumn('author_ID', 'user_id');
});

The error comes from the fact that your class name doesn't correspond to the name of the PHP migration file. Filenames are used to determine the name of the class they contain, so it is important to not rename a class or a file without renaming the other.
Rename your class UpdateUsernameInPostTable to RenameAuthorIdInPostTable and it should work.
If it does not, run composer dumpauto to reload the autoloading file and it will definitely work.

By following the below steps I can be able to rename the column name in Laravel 8
Step 1: Enter the below command to create a new migration file
php artisan make:migration update_author_ID_column --table=posts
Step 2: Write the below code in the created file. Follow the below code for up() function
public function up()
{
Schema::table('employee', function (Blueprint $table) {
$table->renameColumn('author_ID', 'user_id');
});
}
Step 3: Write the Below Code in down() function
public function down()
{
Schema::table('employee', function (Blueprint $table) {
$table->renameColumn('user_id', 'author_ID');
});
}
Step 4: Before running Migration command install the doctrine/dbal dependency
composer require doctrine/dbal
Step 5: finally run migration command.
php artisan migrate

you can use DB statement if you don't want to use doctrine
public function up()
{
DB::statement('ALTER TABLE posts CHANGE author_ID user_id bigint(20) ');
}

Best way would be to check if we have some column in our table or not, just avoid error while migrating;)
public function up()
{
if (Schema::hasColumn('table_name', 'old_col_name'))
{
Schema::table('table_name', function (Blueprint $table)
{
$table->renameColumn('old_col_name', 'new_col_name');
});
}
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
if (Schema::hasColumn('table_name', 'new_col_name'))
{
Schema::table('table_name', function (Blueprint $table)
{
$table->renameColumn('new_col_name', 'old_col_name');
});
}
}

Related

Laravel 8 pivot working only in 1 direction

I got a problem I have done model and migration for 3 tables: movies, actors and actor_movie (pivot)
when Im using from model Actor method movie() it working but don't work from Movie using actor()
class Movie extends Model
{
use HasFactory;
public function actors()
{
return $this->belongsToMany(Actor::class, 'actor_movie');
}
}
class Actor extends Model
{
use HasFactory;
public function movies()
{
return $this->belongsToMany(Movie::class, 'actor_movie');
}
}
movies migration:
public function up()
{
Schema::create('movies', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
}
actor migration:
public function up()
{
Schema::create('actors', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
}
Pivot migration:
public function up()
{
Schema::create('actor_movie', function (Blueprint $table) {
$table->bigInteger('movie_id')->unsigned()->index();
$table->foreign('movie_id')->references('id')->on('movies')->onDelete('cascade');
$table->bigInteger('actor_id')->unsigned()->index();
$table->foreign('actor_id')->references('id')->on('actors')->onDelete('cascade');
$table->primary(['actor_id', 'movie_id']);
$table->timestamps();
});
}
As said in the comments, you are running your tests in a Tinker console.
Tinker console loads all your PHP files and dependencies on startup and keep them in memory.
For your code to be refreshed, you need to kill tinker and restart it

What is the down() function to reverse this Laravel migration that I make?

So, I want to add a column ('Semester_TA') and change the property of this column ('kode_mk') to be unique value, so I created this migration:
public function up()
{
Schema::table('mk', function(Blueprint $table){
$table->string('Semester_TA')->after('sks');
$table->string('kode_mk')->unique();
});
Schema::table('lr2', function(Blueprint $table){
$table->dropForeign(['id']);
});
}
public function down()
{
//
}
I also want to drop/delete this foreign key ('id') that I created as it sometimes give a constraint error in my project. My question is what function down should I write to reverse the update above that i'm about to do in case of migration fails or error?
this is the table "mk" and "lr2" migrations that i use right now:
Schema::create('mk', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('kode_mk');
$table->string('mk');
$table->integer('sks');
$table->integer('semester');
$table->integer('available_seats');
$table->timestamps();
});
Schema::create('lr2', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('k_mk');
$table->string('mk');
$table->string('angkatan');
$table->integer('request_seats');
$table->boolean('status_request');
$table->timestamps();
$table->foreign('id')->references('id')->on('mk');
});
First, you have to create a new migration:
php artisan make:migration Add_column_change_the_property
Then in that migration file up(), try:
public function up()
{
Schema::table('mk', function(Blueprint $table){
$table->string('Semester_TA')->after('sks');
$table->string('kode_mk')->unique();
});
}
Then in the migration file down() try:
public function down()
{
$table->dropColumn('kode_mk');
$table->foreign('id')->references('id')->on('mk');
//
}
Then migrate the file by:php artisan migrate

Laravel Cannot update or delete a parent row a foreign key constraint fails

i am trying to run command php artisan migrate:rollback and it throw me the error cannot update or delete a parent row foreign key constraint fails
there is now issue when i run command php artisan migrate it successfully migrate my all tables but when i run rollback command it throw me the error the error is on my purpose_of_visits migration
public function up()
{
Schema::create('purpose_of_visits', function (Blueprint $table) {
$table->increments('id');
$table->string('purpose', 100);
$table->string('description', 197);
$table->integer('speciality_id')->unsigned()->nullable();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();
$table->softDeletes();
$table->integer('created_by')->unsigned()->nullable();
$table->integer('updated_by')->unsigned()->nullable();
$table->foreign('speciality_id')->references('id')->on('specialities')->onDelete('cascade');
$table->foreign('created_by')->references('id')->on('users')->onDelete('cascade');
$table->foreign('updated_by')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('purpose_of_visits');
}
and my specialities migration:
public function up()
{
Schema::create('specialities', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 50);
$table->string('description',250)->nullable();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();
$table->softDeletes();
$table->integer('created_by')->unsigned()->nullable();
$table->integer('updated_by')->unsigned()->nullable();
$table->foreign('created_by')->references('id')->on('users')->onDelete('cascade');
$table->foreign('updated_by')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('specialities');
}
i cant figure out where is the issue even i am using onDelete('cascade')
your help will be highly appreciated!
Make sure you have speciality_id, created_by and updated_by in the fillable property of your purpose_of_visits model. See docs here.
For example on your model.
protected $fillable = ['speciality_id','created_by','updated_by'];
Remove the foreign key constraints of the table before dropping it.
public function down()
{
Schema::table('purpose_of_visits', function (Blueprint $table) {
$table->dropForeign(['speciality_id']);
$table->dropForeign(['created_by']);
$table->dropForeign(['updated_by']);
});
Schema::dropIfExists('purpose_of_visits');
}
Sorry For the Late reply There are Two Situation Where this error can be thrown
For Eg:
I have tables such as posts, authors
And here is my post table Migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->unsignedInteger('author_id');
$table->foreign('author_id')->references('id')->on('authors')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
and here is my authors table migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAuthorsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('authors', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('authors');
}
}
Situation 1:
now if the posts table migration runs before the authors table migration it my throw the error
Situation 2:
in some cases if you miss unsigned it may throw error
Solution1:
use
$table->unsignedInteger('speciality_id');
$table->unsignedInteger('speciality_id');
$table->foreign('author_id')->references('id')->on('specialities')->onDelete('cascade');
instead of this
$table->integer('speciality_id')->unsigned()->nullable();
$table->foreign('speciality_id')->references('id')->on('specialities')->onDelete('cascade');
if it again fails use this
try composer dumpautoload
adn then
Schema::disableForeignKeyConstraints();
At the beggining of the migration
and at the end
Schema::enableForeignKeyConstraints();
eg: you migration may look like
public function up()
{
Schema::disableForeignKeyConstraints();
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
Schema::enableForeignKeyConstraints();
}
and if the same error throws please attach Error Screenshot and commet below
Hope it helps

Laravel: 1060 Duplicate column name while running migrations

I am getting the following error when running migrations:
PDOException::("SQLSTATE[42S21]: Column already exists: 1060 Duplicate
column name 'role_id'")
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
if(!Schema::hasTable('users')) {
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Schema::table('users', function (Blueprint $table) {
$table->integer('role_id')->unsigned();
$table->string('first_name')->nullable();
$table->string('middle_name')->nullable();
$table->string('last_name')->nullable();
$table->string('city')->nullable();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('role_id');
});
}
}
I have deleted most of the migrated tables as it gives duplication issues. Could that be related to my existing problem ?
try running these commands in your terminal:
composer dump-autoload // updates whatever you changed in your migration
php artisan migrate:fresh // migrates migration from the start
if these doesn't not work, post your column structure so we can understand more about your problem.

Removing column from database in Laravel 5+

I've a blog for which the articles table Schema is defined like this:
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('title');
$table->string('thumb')->nullable();
$table->text('excerpt');
$table->text('body');
$table->string('slug')->unique();
$table->integer('comment_count')->unsigned()->default(0);
$table->integer('view_count')->unsigned()->default(0);
$table->timestamps();
$table->softDeletes();
}
public function down()
{
Schema::drop('articles');
}
I want to drop the columns comment_count and view_count without losing existing data in the table
I defined a new migration like this:
class RemoveCommentViewCount extends Migration
{
public function up()
{
//nothing here
}
public function down()
{
Schema::table('articles', function($table) {
$table->dropColumn('comment_count');
$table->dropColumn('view_count');
});
}
}
and I did php artisan migrate . It did migrate successfully, but the two columns are not dropped.
What am I doing wrong? How can I drop those columns without losing the existing data in the table?
Your migration must look like this:
class RemoveCommentViewCount extends Migration
{
public function up()
{
Schema::table('articles', function($table) {
$table->dropColumn('comment_count');
$table->dropColumn('view_count');
});
}
public function down()
{
Schema::table('articles', function($table) {
$table->integer('comment_count');
$table->integer('view_count');
});
}
}
The dropColumn in the up method, because with new migration you want to delete this columns. If you make a rollback, you have another time the two columns
Even you can drop the multiple columns in a single line by passing the array column to dropColumn function.
class RemoveCommentViewCount extends Migration
{
public function up()
{
Schema::table('articles', function($table) {
$table->dropColumn(['comment_count', 'view_count']);
});
}
public function down()
{
Schema::table('articles', function($table) {
$table->integer('comment_count');
$table->integer('view_count');
});
}
}
In case you have a foreign key constraint, then drop first the foreign key index association and then can pass the column to dropColumn function with others like following.
public function up()
{
Schema::table('customer_orders', function($table) {
$table->dropForeign(['product_id']);
$table->dropForeign(['shipping_address_id']);
$table->dropColumn(['product_id', 'shipping_address_id', 'column1', 'column2']);
});
}
Create remove column migration
php artisan make:migration RemoveCommentViewCount
The down method is for rollbacks, so add dropColumn in your up() function and reverse in down()
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class RemoveCommentViewCount extends Migration
{
public function up()
{
if (Schema::hasColumn('comment_count', 'view_count')){
Schema::table('articles', function (Blueprint $table) {
$table->dropColumn('comment_count');
$table->dropColumn('view_count');
//OR
$table->dropColumn(['comment_count', 'view_count']);
});
}
}
public function down()
{
Schema::table('articles', function($table) {
$table->integer('comment_count');
$table->integer('view_count');
});
}
}
Check laravel documentation on dropping columns migrations
I had a similar issue, I edited the initial migration, that is the initial table schema, removed the columns and then run php artisan migrate:refresh and it worked for me
Just add this code into your down() function in migration.php file
Schema::table('articles', function (Blueprint $table) {
$table->integer('comment_count')->unsigned()->default(0);
$table->integer('view_count')->unsigned()->default(0);
});
and then run --> php artisan migrate:rollback

Resources