Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added dropColumnsIfExists and dropColumnIfExists #53305

Open
wants to merge 3 commits into
base: 11.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/Illuminate/Database/Schema/Blueprint.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Illuminate\Database\Schema\Grammars\Grammar;
use Illuminate\Database\Schema\Grammars\MySqlGrammar;
use Illuminate\Database\Schema\Grammars\SQLiteGrammar;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Fluent;
use Illuminate\Support\Traits\Macroable;

Expand Down Expand Up @@ -427,6 +428,26 @@ public function dropColumn($columns)
return $this->addCommand('dropColumn', compact('columns'));
}

/**
* Indicate that the given columns should be dropped if exists.
*
* @param array|mixed $columns
* @return \Illuminate\Support\Fluent
*/
public function dropColumnIfExists($columns)
{
$current = Schema::getColumnListing($this->getTable());

$columns = is_array($columns) ? $columns : func_get_args();
$columns = array_filter($columns, fn ($column) => in_array($column, $current));

if (empty($columns)) {
return new Fluent();
}

return $this->addCommand('dropColumn', compact('columns'));
eusonlito marked this conversation as resolved.
Show resolved Hide resolved
}

/**
* Indicate that the given columns should be renamed.
*
Expand Down
14 changes: 14 additions & 0 deletions src/Illuminate/Database/Schema/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,20 @@ public function dropColumns($table, $columns)
});
}

/**
* Drop columns from a table schema if exists.
*
* @param string $table
* @param string|array $columns
* @return void
*/
public function dropColumnsIfExists($table, $columns)
{
$this->table($table, function (Blueprint $blueprint) use ($columns) {
$blueprint->dropColumnIfExists($columns);
});
}

/**
* Drop all tables from the database.
*
Expand Down