Prohibit running destructive DB commands in Laravel
It’s always a good idea to follow best practices when it comes to software development. One of the best practices is to restrict the running of destructive commands on your servers, intentionally or unintentionally.
Database commands, for instance, are destructive commands which can cause data loss or corruption. So, we should better restrict running them on our servers. Especially on a production server.
Laravel got us covered in this regard. I recently learned about the DB::prohibitDestructiveCommands()
method which lets us prohibit running destructive commands on our servers.
Here’s how we can use it to restrict the destructive commands in production environments.
namespace App\Providers;
use Illuminate\Support\Facades\DB;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
DB::prohibitDestructiveCommands(
$this->app->isProduction()
);
}
}
This command restricts running the following commands.
db:wipe
migrate:fresh
migrate:refresh
migrate:reset
And if you run one of these commands, it will throw the warning message: “This command is prohibited from running in this environment.”
👋 Hi there! This is Amit, again. I write articles about all things web development. If you enjoy my work (the articles, the open-source projects, my general demeanour... anything really), consider leaving a tip & supporting the site. Your support is incredibly appreciated!