I am trying to use Laravel Migration to create SQL tables but it won't let me.
Here is the error:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table
'mytable' already exists
Here is my code:
Schema::create('mytable', function (Blueprint $table) {
$table->increments('id');
$table->foreign('othertable_id')
->references('id')->on('othertable')
->onDelete('cascade');
$table->string('variable');
$table->timestamps();
});
}
{
Schema::drop('mytable');
}
I have also checked if other migrations are called "mytable" but they are not, so I am not sure where this come from.
I tried the following:
First
php artisan migrate:refresh
Which gave me an error
And then I deleted the entire database altogheter and used:
php artisan migrate
And still got the error
In laravel 5.5 and > you can use:
$ php artisan migrate:fresh
// ( not migrate:refresh wich is a different command)
This command first drops all tables and then reruns all migrations
If you have the table in DB and dont want migrate create it, you can ignore it by check Schema::hasTable before create
public function up()
{
if(Schema::hasTable('products')) return; //add this line to migration file
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
}
I had neither removed the migration entry nor dropped the table manually from the database
In my case, the solution is open up the tinker from the composer
$ php artisan tinker
>>> Schema::drop('users')
>>> Schema::drop('password_resets')
>>> Schema::drop('orders')
>>> exit
php artisan migrate
Here is the result of the above commands executed
nishanth#localhost:~/Desktop/html/hutch$ php artisan migrate
In Connection.php line 647:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users'
alre ady exists (SQL: create table users (id int unsigned not
null auto_incr ement primary key, name varchar(255) not null,
email varchar(255) not n ull, password varchar(255) not null,
remember_token varchar(100) null, created_at timestamp null,
updated_at timestamp null) default character set utf8mb4
collate utf8mb4_unicode_ci)
In Connection.php line 449:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users'
already exists
nishanth#localhost:~/Desktop/html/hutch$ php artisan migrate:rollback
Nothing to rollback.
nishanth#localhost:~/Desktop/html/hutch$ php artisan tinker
Psy Shell v0.8.17 (PHP 7.1.20-1+ubuntu16.04.1+deb.sury.org+1 — cli) by Justin Hileman
>>> Schema::drop('users')
=> null
>>> Schema::drop('password_resets')
=> null
>>> Schema::drop('orders')
=> null
>>> exit
Exit: Goodbye.
nishanth#localhost:~/Desktop/html/hutch$ php artisan migrate
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table
Migrating: 2018_08_18_071213_create_orders_table
Migrated: 2018_08_18_071213_create_orders_table
nishanth#localhost:~/Desktop/html/hutch$
Also define the method down(), if it doesn't exist.
Otherwise, it'll show
SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'XYZ.ABC' (SQL: drop table ABC)
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('ABC');
}
Try this,
Add following line :Schema::dropIfExists('mytable'); inside the Up() function at the very beggining exactly before creating schema for the mytable. i.e. before following code. Schema::create('mytable', function (Blueprint $table)
do composer dump, remove the table manually from the database and also remove the migration entry for the the table you want to remove from the migration table and rerun the migration again to see what happens.
The error says that the table mytable does already exist in the DB. You should rollback the migration:
php artisan migrate:rollback
And migrate again:
php artisan migrate
in my case, I need to dump the SQL schema,
run this command:
php artisan schema:dump
then run PHP artisan migrate command again
go to app>Providers>AppServiceProvider.php and copy paste this at the top:
use Illuminate\Support\Facades\Schema;
then go to function inside of it named 'Boot()' and copy paste this one:
Schema::defaultStringLength(191);
now go to your your database and delete your database completely, then go to console:
php artisan cache:clear
php artisan config:cache
then create a new database with same name and go back to consol and write :
php artisan migrate (congrats your database now shows em all)
Related
I have a migration in my laravel project where I rename fields. This migration works perfectly fine on mysql and most database drivers I've tested (also my local sqlite), for any reason the github ci runner seems to have a problem with the syntax, I believe either caused by an version mismatch or because laravel generates a faulty sql statement. This is my migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('user_weights', function (Blueprint $table) {
$table->renameColumn('weight', 'weight_raw');
});
Schema::table('user_heights', function (Blueprint $table) {
$table->renameColumn('height', 'height_raw');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('user_weights', function (Blueprint $table) {
$table->renameColumn('weight_raw', 'weight');
});
Schema::table('user_heights', function (Blueprint $table) {
$table->renameColumn('height_raw', 'height');
});
}
};
My github workflow looks like this:
on:
push:
branches:
- master
- feature/*
- hotfix/*
pull_request:
branches:
- master
name: CI
jobs:
phpunit:
runs-on: ubuntu-latest
container:
image: kirschbaumdevelopment/laravel-test-runner:8.1
steps:
- uses: actions/checkout#v1
with:
fetch-depth: 1
- name: Install composer dependencies
run: |
composer config "http-basic.nova.laravel.com" "${{ secrets.NOVA_USERNAME }}" "${{ secrets.NOVA_LICENSE }}"
composer install --no-scripts
- name: Prepare .env
run: cp .env.testing .env
- name: Generate key
run: php artisan key:generate
- name: Directory Permissions
run: chmod -R 777 storage bootstrap/cache
- name: Mark app folder as safe directory
run: git config --global --add safe.directory /__w/fitness-backend-neu/fitness-backend-neu
- name: Create Database
run: |
mkdir -p database
touch database/database.sqlite
php artisan migrate
- name: Run Testsuite
run: vendor/bin/phpunit tests/
- name: Run Pint
run: vendor/bin/pint --test
The workflow crashes in the database migration with the following error:
In Connection.php line 759:
SQLSTATE[HY000]: General error: 1 near "0": syntax error (SQL: CREATE TABLE
user_weights (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, user_id VARCH
AR(255) NOT NULL COLLATE BINARY, weight_raw DOUBLE PRECISION NOT NULL, date
DATE NOT NULL, created_at DATETIME DEFAULT NULL, updated_at DATETIME DEFAU
LT NULL, CONSTRAINT 0 FOREIGN KEY (user_id) REFERENCES users (id) ON UPDATE
NO ACTION ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE))
In Connection.php line 538:
SQLSTATE[HY000]: General error: 1 near "0": syntax error
Since the error occurred with the "user_id" relation, I already tried to remove the relation before renaming and recreating the relation right after the rename process. Since sqlite doesn't support removing foreign key constraints, this didn't work.
I also tried reproducing this error using act. Act is a local ci runner which also interprets the GitHub workflow file. With the exact same setup ran by act, I still wasn't able to reproduce this error. Everything is working fine (Act, PHPUnit, Migration on local environment, Migration on production environment) except GitHub Actions.
I just saw, that the exact same migration ran through GitHub action previously and didn't fail. It just started failing after some other commits.
I found a workaround, since laravel seems to generate a faulty sql statement in this case. I added the following code into my migration to catch the sql statement on sqlite connection and run a "sqlite only" query.
if (config('database.default') === 'sqlite') {
DB::statement('ALTER TABLE user_weights RENAME COLUMN weight TO weight_raw;');
DB::statement('ALTER TABLE user_heights RENAME COLUMN height TO height_raw;');
return;
}
I did the same for the reverse migration.
I am new to laravel.
I am working on laravel version 6.
I have created migration.
It works nicely the first time, but if i change something in the migration file and then i run php artisan migrate it shows nothing to migrate.
I tried php artisan migrate --path as well but it does not work.
To make it work i have to delete the migration file and create it again.
I don't want to use php artisan migrate:fresh.
what should i do to run only one migrations file which has been changed?
When you run php artisan migrate it'll check migration table if there is no new file in the migration folder it'll show you nothing to migrate.
If you want to rollback last migration.
To rollback the latest migration operation, you may use the rollback command. This command rolls back the last "batch" of migrations, which may include multiple migration files:
php artisan migrate:rollback
It'll delete the last created table.
The migrate:reset command will roll back all of your application's migrations:
php artisan migrate:reset
The migrate:fresh command will drop all tables.
php artisan migrate:fresh
php artisan migrate:fresh --seed
more info : document
Sadly impossible. The best workaround is to use seeders and use php artisan db:seed after you use php artisan migrate:fresh. Why don't you want to use that?
there is two things to do you that you can use
1. In your database there is a table called migrations. Delete the rows from there which one is you want to migrate. That should be there.
2.create a folder inside of database/migrations/folder. And put the migrations file inside the folder then in your command prompt run this below command:
php artisan migrate:refresh --path=database/migrations/folder
option 2 is better than the option 1. I always use this. So i recommend option 2. This should be work
If you have seeder data then you simply do: php artisan migrate: fresh -- seed . It help to re-migrate your migration with seeder data
You didn't understand well migrations mechanics.
but if i change something in the migration file and then i run php artisan migrate it shows nothing to migrate
You write migration to make some changes in database and run it once. If you want to do next updates to database you need next migration.
During development process you can rerun migrations by php artisan migrate:fresh, but on production make sure your migration makes everything you want.
Laravel stores informations about migrations in database in table 'migrations'. If you want to reset some migrations files you can try deleting or edit some records in that table.
Have you checked that the migration has already run or not in the migration table.
If its run then there will be a row respective to your migration.
If you do changes to an old migration than nothing will be reflected when you run command php artisan migrate, as it has already been migrated.
For every modification on existing (already migrated tables) you will have to make a new migration with modifications only. If you have "users" table migration 2014_10_12_000000_create_users_table like:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
and you need to split "name" column, will have to php artisan make:migration alter_table_users --table="users" and add what you want to change:
Schema::table('users', function (Blueprint $table) {
$table->renameColumn('name', 'first_name'); // rename column
$table->string('last_name'); // add new column });
Reverse
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->renameColumn('first_name', 'name');
$table->dropColumn('last_name');
});
}
Nou you can use php artisan migrate
Documentation: https://laravel.com/docs/6.x/migrations#modifying-columns
No one replied question "Akshay Rathod" but "Militaru" replied exactly what he need php artisan make:migration alter_table_users --table="users" and copy you new fields inside the up() function as under
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('userimage')->nullable();
$table->string('contact_no')->nullable();
$table->string('website')->nullable();
$table->string('country_id')->nullable();
$table->string('timezone')->nullable();
$table->string('currency')->nullable();
$table->string('communication_email')->default(1);
$table->string('communication_phone')->default(0);
$table->string('allow_marketing')->default(0);
});
}
i am new to laravel and i ran the auth file to make a register and login etc...
i have 3 migrations file inside the migrations folder: user table reset_password table and user_profile table: the problem is when i ran: php artisan migrate it only create the user table without the 2 other table so i tried these commands:php artisan migrate:rollback, php artisan migrate:refresh, php artisan config:cache php artisan config cache:clear and then i ran :php artisan migrate and only user table was created... any idea? thank you
I am also facing the same issue, while you are running php artisan migrate, the command starts migrating the table and while migrating users table it is throwing some error like:
[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key
was too long; max key length is 767 bytes (SQL: alter table
users add unique users_email_unique(email))
so, only user table is migrated and the process stops with the above error. If this is the issue, then you have to solve it and after that delete the users table and again migrate, every thing will be fine.
To fix the above issue, all you have to do is to edit your app/Providers/AppServiceProvider.php file and add to the boot method a default string length like:
use Illuminate\Support\Facades\Schema;
function boot()
{
Schema::defaultStringLength(191);
}
and again migrate, everything will be fine.
I Found the solution for this
First set this in App/Providers/AppServiceProvider.php
use Illuminate\Support\Facades\Schema;
public function boot()
{
Schema::defaultStringLength(191);
}
Then Migrate Cmd And at Last
php artisan migrate:fresh
after that migration works
I am a new learner of Laravel.And I follow the tutorial to create a articles table.Here's part of my code in /database/migrations/2017_02_13_145946_create_article_table.php
public function up()
{
//
Schema::create('articles', function(Blueprint $table)
{
$table->increments('id');
$table->string('title');
$table->text('body')->nullable();
$table->integer('user_id');
$table->timestamps();
});
}
When I run php artisan migrate the table was not created.I googled the problem and ran php artisan migrate:reset command to delete all the tables.When I ran php artisan migate command again.It shows
Migrated: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_100000_create_password_resets_table
Migrated: 2017_02_13_145946_create_article_table
But nothing was created but only updated the record of migrations table.The table user and password_resets was also not created.
Any ideas what I might be doing wrong?
It is because of Table column(values) length is by default 1071 which not accept by mysql
To clear this problem go to mysql and delete all the tables.
Go to your application(project) folder => app => Providers
write this on top of your AppServiceProvider.php file.
//edit:yrs:- Needed for edit
use Illuminate\Support\Facades\Schema;
write this inside the boot method
//edit:yrs:-we can edit column sizefor tables here
Schema::defaultStringLength(150);
then come to console and execute the
*command />php artisan migrate:status and see the run status is y or n if it is n then execute
*command />`php artisan migrate`
*command />`php artisan migrate:status` and then
*command />`php artisan migrate:refresh` and then
*command />`php artisan migrate:status`
that's all your done with createing with tables in mysql
I normally try several things:
In the console do rollbacks till you get 'nothing to rollback':
php artisan migrate:rollback
Then, check your article migration file and look for down function (if you haven't one you need to add it)
public function down()
{
// Drop articles table
Schema::drop('articles');
}
Save your migration article file(I know it sounds dumb, but it happened to me before). I would recommend to change the name of the file also, from:
2017_02_13_145946_create_article_table.php, to:
2017_02_13_145946_create_articles_table.php
Use:
composer dump-autoload
Go to your database(laravel_db in this case) and check if there are any table(Mysql Console):
show databases;
use laravel_database:
show tables;
If there are not any table but migrations, delete it using:
drop table migrations;
Once you have the database empty, run the migrations from console:
php artisan migrate
Finally, if not errors being trowed, check the tables created(Mysql Console):
show tables;
I installed migrations with php artisan migrate:install then created a migration with the php artisan migrate:make create_teams_table command. Now I try to run them with the following command that I made according to the official documentation:
php artisan migrate --path=app/foo/migrations/2014_01_21_143531_create_teams_table.php
This gives me the following on the console:
Nothing to migrate.
The migrations table in the database is empty and the new table isn't created neither. I don't understand why the documentation says foo in the path. What does foo mean and where does it comes from? First I tought that the path is wrong because of the foo thing and as I know the path is relative to the app folder so I changed it to app/database/migrations but it doesn't work. I also tried a lot of other path combination but none of them worked.
Did I entered the wrong path? In this case shouldn't the console show some other kind of helpfull message? What does foo mean? How can I run my migration?
Try this:
First:
php artisan migrate:reset
Rolled back: 2014_03_28_142140_user_table
Nothing to rollback.
second:
php artisan migrate
Migrated: 2014_03_28_142140_user_table
check the database.
That foo thing is just an example. Laravel will look for migrations to run in app/database/migrations on default. Try removing that --path parameter and see if it works.
You don't need to move the migration file anywhere, just change its filename; for example, increase time integer and then run the migrate command with the path pointing to the migration. e.g: php artisan migrate --path="database/migrations/2019_07_06_145857_create_products_table.php"
What helped me:
php artisan config:cache
php artisan migrate
The path argument is for creating a migration for example:
php artisan migrate:make create_user_table --path=app/database/migrations/user_migrations/
But it is not documented to use while running the migrations, as it was in prior versions of laravel.
Dropping the --path argument should work in your case
need to delete 2014_01_21_143531_create_teams_table of migrations table.
go to database(phpmyadmin)
open your database name.
3.open migrations table.
delete the 2014_01_21_143531_create_teams_table row
For anyone who still cannot migrate their database:
Assume you have a file to migrate abc_migrate.php.
Firstly put your file inside the new folder named abc_folder.
Then, enter this command
php artisan migrate --path=database/migrations/abc_folder/.
You don't have to add file name at last of the directory path.
Done. Hope it helps.
use
php artisan migrate:fresh
it would refresh your database and run your all migrations again
Note:, don't do this in production, it will wipe your all your data. so before running this command do have a backup of your data. in fact, have backup data whenever you are touching database in production.
All you need to do is refresh the migration
php artisan migrate:refresh --path=app/foo/migrations/2014_01_21_143531_create_teams_table.php
At least in Laravel 7, you have to add ".php" at the end of the name of the migration.
Example:
php artisan migrate --path=database/migrations/yyyy_mm_dd_table_name.php
Hope this answer help somebody.
What's happening here is the filename for the migration is cached, and so even though you are changing the migration file, it is not seeing any changes, and so thinks there is nothing to migrate.
There's two ways to fix this:
You can change the file name slightly from from 2014_01_21_143531_create_teams_table.php to 2014_01_21_143532_create_teams_table.php (incrementing the number by 1) and then run php artisan migrate...
or
You can run php artisan optimize:clear to flush the cache and then run php artisan migrate:fresh to do a fresh migration.
Hope this helps!
The problem arises if the migrations table in the database is empty.
So the solution is open up the tinker from the composer
$ php artisan tinker
>>> Schema::drop('users')
>>> Schema::drop('password_resets')
>>> Schema::drop('orders')
>>> exit
php artisan migrate
Here is the result of the above commands executed
nishanth#localhost:~/Desktop/html/hutch$ php artisan migrate
In Connection.php line 647:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users'
alre ady exists (SQL: create table users (id int unsigned not
null auto_incr ement primary key, name varchar(255) not null,
email varchar(255) not n ull, password varchar(255) not null,
remember_token varchar(100) null, created_at timestamp null,
updated_at timestamp null) default character set utf8mb4
collate utf8mb4_unicode_ci)
In Connection.php line 449:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users'
alre ady exists
nishanth#localhost:~/Desktop/html/hutch$ php artisan migrate:rollback
Nothing to rollback.
nishanth#localhost:~/Desktop/html/hutch$ php artisan tinker
Psy Shell v0.8.17 (PHP 7.1.20-1+ubuntu16.04.1+deb.sury.org+1 — cli) by Justin Hileman
>>> Schema::drop('users')
=> null
>>> Schema::drop('password_resets')
=> null
>>> Schema::drop('orders')
=> null
>>> exit
Exit: Goodbye.
nishanth#localhost:~/Desktop/html/hutch$ php artisan migrate
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table
Migrating: 2018_08_18_071213_create_orders_table
Migrated: 2018_08_18_071213_create_orders_table
nishanth#localhost:~/Desktop/html/hutch$
Also define the method down(), if it doesn't exist.
Otherwise, it'll show
SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'XYZ.ABC' (SQL: drop table ABC)
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('ABC');
}
In my case, i just had to delete a row from my migrations table and then execute
php artisan migrate --path=app/foo/migrations/2014_01_21_143531_create_teams_table.php