So I have an issue where I have a multi-tenant application, and I have a system where I can manage all of these tenants with standard CRUD operations. I want to be able to drop the tenant databases when the tenant gets deleted but I cannot seem to find anything in the documentation about being able to do this, nor can I find a series of methods in the API documentation which can be used.
I have seen the below online (the only information I can find), but it's 2 years old but all of these methods have either been deprecated or have been moved in Laravel 6.
Schema::getConnection()->getDoctrineSchemaManager()->dropDatabase("`{$database_name}`");
Through my own tests, running the following command does work.
DB::statement('DROP DATABASE `foo`');
What I can't do though is bind a variable to this statement:
DB::statement(DB::raw('DROP DATABASE ?', $database_name));
I also want to use the standard Laravel query builder instead of sanitising the information myself. So ideally I would like to be able to do something like this:
DatabaseManager::dropDatabase($database_name);
or this:
$database = DatabaseManager::connect($database_name);
$database->dropDatabase();
My guess would be that I need to create a new connection to MySQL where I'm not connecting directly to an individual database. Then execute a command to drop a database, and then close the connection.
I will be looking to build this myself, but just wondering if anyone had any thoughts on this one, or if anyway has done this before? All help is much appreciated.
DB::statement(...)
and that seems to work fine. – Creativityartisan
is a "user" (even if it's a trusted one). It's not a Laravel feature though, MySQL doesn't support prepared statements with the database/table/column name as the parameter. Backtick escaping is the only thing you can do, but it's also a sufficient thing to do (just make sure you also remove backtick characters from$databaseName
). – Lightweight