How to delete all the tables in a database in one shot in laravel.
For Migration we use-
Artisan::call('migrate', ['--force' => true]);
but for deleting all the tables is there any-
Thank You
php artisan db:wipe
It is a quick way to drop all the tables, their types and views if you’re using Laravel 6.x
Full description:
$ php artisan db:wipe {--database=} {--drop-views} {--drop-types} {--force}
database - The database connection to use
drop-views - Drop all tables and views
drop-types - Drop all tables and types (Postgres only)
force - Force the operation to run when in production
It was implemented on Aug 20, 2019
This change has also affected the db:fresh command’s functionality internally. Now it just calls db:wipe and then migrate.
Why not use this:
Artisan::call('migrate:reset', ['--force' => true]);
You can also use migrate:fresh in newer Laravel versions.
The migrate:fresh command will drop all tables from the database and then execute the migrate command
https://laravel.com/docs/7.x/migrations
In Laravel 5.6 documentation they have specified the following,
The migrate:reset command will roll back all of your application's migrations:
php artisan migrate:reset
You can do it with Controller Method
public function drop_tables(){
DB::statement("SET FOREIGN_KEY_CHECKS = 0");
$tables = DB::select('SHOW TABLES');
foreach($tables as $table){
Schema::drop($table->Tables_in_DbName); /// replace <DbName> according to your Databse Name
echo 'Table '.$table->Tables_in_DbName.' Droped. <br>'; // here too
}
DB::statement("SET FOREIGN_KEY_CHECKS = 1");
}
invoke it as per your requirement.
This will Drop all the tables that are present/existed in the Current Database
Here's an improvement on dipenparmat12's answer. It avoids the issues of the database name, and also foreign key constraints.
\DB::statement('SET FOREIGN_KEY_CHECKS = 0;');
$tables = \DB::select('SHOW TABLES');
foreach($tables as $table){
$table = implode(json_decode(json_encode($table), true));
\Schema::drop($table);
echo 'Dropped `'.$table . '`. ';
}
\DB::statement('SET FOREIGN_KEY_CHECKS = 1;');
The accepted answer doesn't work in the case where you've misnamed a table in a migration. I myself did this during development; which is why I landed on this stack exchange question. I put a typo in the table in the op() method, but named it properly in the down() method. Here's an example.
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('misnamed', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->uniq();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('properly_named');
}
This will cause rollbacks, resets, and refreshes to fail, because the migrator tries to drop a table that doesn't exist:
$ artisan migrate:refresh
In Connection.php line 664:
SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'app.properly_named' (SQL: drop table `properly_named`)
In Connection.php line 458:
SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'app.properly_named'
$ artisan migrate:rollback
In Connection.php line 664:
SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'app.properly_named' (SQL: drop table `properly_named`)
In Connection.php line 458:
SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'app.properly_named'
$ artisan migrate:reset --force
In Connection.php line 664:
SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'app.properly_named' (SQL: drop table `properly_named`)
In Connection.php line 458:
SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'app.properly_named'
I suspected the only way to un-break the migrations would be to drop the tables manually, in SQL, but I didn't want to go through the hassle of typing out those statements. If I make a mistake once, I'm pretty sure I'll make it again, so I wanted a way to perform an SQL DROP of all the tables, and avoid all the logic of migrations and rollbacks.
dipenparmar12's answer was a first step in the right direction; the only problem for me was that I had foreign keys, and MySQL won't drop tables with foreign key relationships without those relationships being specifically dropped first.
However, you can tell MySQL to ignore foreign key checks when dropping tables, so that's what my answer does.
If you mess up your migration to the point where these commands break, and want to just drop all the tables and start fresh, this answer will get the job done.
Related
While creating my database according to the eloquent standard, I ran into the problem that my table_name and id column name combined would be longer as 64 characters.
very_long_table_name.very_long_column_name_id
So I used a shorter column name as the foreign key in my Intermediate Table.
Migration file:
$table->unsignedBigInteger('short_id');
$table->foreign('short_id')->references('id')->on('very_long_table_name');
That worked fine, yet now I would like to insert a connection
Seeder.php:
$x->very_long_table_name()->attach($other_table_name->id);
I get the error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'very_long_column_name_id' in 'field list' (SQL: insert into very_long_table_name (just_an_id, very_long_column_name_id) values (1, 1))
What I would want is that it would use the column short_id instead of very_long_column_name_id to insert this, is there any cool way to fix this? or do I need to insert and query the connection manually if I keep the long names?
Like #Tim points out in the comments this needs to be done in the Model VeryLongTableName.php where you define the relationship:
public function very_long_table_name() {
return $this->belongsToMany(Model::class, 'very_long_table_name', 'local_id', 'short_id');
}
for a homework i have to do a todolist in laravel 7 i do my db but when i try to create a foreign key to the table task
and a table categories
the program fail with the formula :"SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table 'categories' (SQL: alter table tasks add constraint tasks_category_id_foreign foreign key (categ
ory_id) references categories (id) on delete cascade)"
i've done it a lot of time but i don't understand why i doesn't work if someone could explains
the right way to do it
The migration is trying to create the tasks table before categories, the categories table still doesn't exist at the time it tries to create the FK.
Swap the order of your migrations changing its filename. Each migration file at database/migrations has a date-time before the name. Alter it so the tasks migration has a date greater than the categories one.
will Gus Costa is right and you should do as he says but i want to add that your
foreign key should be unsigned
and here you will find some good answers
"General error: 1005 Can't create table" Using Laravel Schema Build and Foreign Keys
// CREATING TABLE
Schema::create('table_name', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->integer('field_id')->unsigned; //for field that contains foreign key constraint
});
// FOREIGN KEY CONSTRAINT
Schema::table('stock', function ($table) {
$table->foreign('field_id')->references('id')->on('some_table')->onDelete('cascade')->onUpdate('cascade');
});
enter image description herei have 3 tables made in Voyager and with BREAD (news - catg - news_catg).
My 'news' Table have Relationship (Belongs To Many) to 'catg' and the news_catg is the pivot table
Every think is working will except the Delete i have to Delete the Records manually from the pivot table it should be automatic like add and update
finally i found that there is bug in Voyager and there is no way to fix this issue from the admin panel so i did the flowing :
1 - deleted the Pivot table .
2- create new migration file in my app
3 -
` Schema::create('Relation table name', function (Blueprint $table) {
$table->integer('first table id')->unsigned();
$table->foreign('first table id')->references('id')
->on('first table')->onDelete('cascade');
$table->integer('second table id')->unsigned();
$table->foreign('second table id')->references('id')->on('second table');
});`
Relation table name should be like :secondtablename_firsttablename
for ex : catgs_news or it wont work !!!
and the first table id should be tablename_id like news_id
4- then you go to voyager and it will work but you have to edit the new table and add timestamps and you dont have to make bread for it
You can use the detach() function to delete data from pivot table.
There is my migration. I want id field being auto-incremented but not primary. Is it possible? This migration throws an exception Syntax error or access violation: 1075 Incorrect table definition; there can be only one auto column and it must be defined as a key
Schema::create('tests', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('project_id');
$table->unsignedInteger('model_id');
$table->timestamps();
$table->dropPrimary('id');
$table->foreign('project_id')
->references('id')
->on('projects')
->onDelete('cascade');
$table->primary(['project_id', 'model_id']);
});
This is not Laravel error. you can't have two auto increment column in mysql table. (of course if you are using mysql) but I think none of any relational database gives you ability to have two auto increment columns.
But there is another way to do that.
look at this question
This is not a Laravel error but a MySQL error. As the error message says: it must be defined as a key. You are dropping the primaryKey constraint on the id column. You should try setting it as an index.
try the following $table->unsignedInteger('id')->index()->autoIncrement();. This will make it an AI integer and also an index but not a PK.
I'm running migrations on Laravel 5.1 and am switching DBs from Mysql to Postgres.
Typically I could set foreign key checks to 0 prior to running down migrations as such:
- DB::statement('SET FOREIGN_KEY_CHECKS = 0');
- Do stuff
- DB::statement('SET FOREIGN_KEY_CHECKS = 1');
Postgres does not offer this.
In running down migrations, I get error:
Dependent objects still exist: 7 ERROR: cannot drop table table2 because other objects depend on it
DETAIL: constraint table1_table2_table1_id_foreign on table table1_table2 depends on table table2
HINT: Use DROP ... CASCADE to drop the dependent objects too. (SQL: drop table "table2")
Question: This complaint is curious to me as I set ->onDelete('cascade'); on the foreign key creations. Why is this happening?
Snippets:
Create Table1 Table:
...
public function down()
{
Schema::drop('table1_table2');
Schema::drop('table1');
}
Create Table2 Table (Called after table 1 migration):
...
public function down()
{
Schema::drop('table2');
}
Create Foreign Keys Table (last migration to be called)
public function up()
{
Schema::table('table1_table2', function(Blueprint $table)
{
$table->foreign('table1_id')->references('id')->on('table1')->onDelete('cascade');
$table->foreign('table2_id')->references('id')->on('table2')->onDelete('cascade');
});
...
}
public function down()
{
...
Schema::table('table1_table2', function(Blueprint $table)
{
$table->dropForeign('table1_id');
$table->dropForeign('table2_id');
});
...
}
This complaint is curious to me as I set ->onDelete('cascade'); on the foreign key creations. Why is this happening?
The key term here is "on delete" - when you delete a row from one table, that option will determine whether rows with foreign keys referencing that row will be deleted as well.
However, your change script is not deleting rows, it is dropping the table. This is therefore a different event, not effected by the ON DELETE option on the foreign key.
The CASCADE mentioned in the hint is a keyword on the DROP TABLE statement, discussed in the manual under "Dependency Tracking":
Key quotes:
When you create complex database structures involving many tables with foreign key constraints, views, triggers, functions, etc. you implicitly create a net of dependencies between the objects. For instance, a table with a foreign key constraint depends on the table it references.
and:
if you do not want to bother deleting all the dependent objects individually, you can run DROP TABLE products CASCADE; and all the dependent objects will be removed, as will any objects that depend on them, recursively. In this case, it doesn't remove the orders table, it only removes the foreign key constraint.
and:
Almost all DROP commands in PostgreSQL support specifying CASCADE.
For my case; you can get this error with this scenario;
If your table seems rollbacked in migration table (ex: maybe forget drop function first time) but table still exists on database you can get this error. migrate:fresh command will fail with given error message for this scenario.
You can drop table manually or add a row to migration table with that migration name and everything will be working normally.