The laravel app that I'm working on needs to have a dedicated database for each user (better for debugging and managing).
So basically, the user login on the database specified (DB_DATABASE) in the .env file, and and then all other controller have a middleware that change the laravel database to use the user database (that has been created programmatically when the user registered the first time).
if (Auth::check())
{
$user = Auth::user();
$userDatabase = $user->database;
Config::set('database.connections.mysql.database', $userDatabase);
DB::purge('mysql');
DB::reconnect('mysql');
try
{
$pdo = DB::connection('mysql')->getPdo(); // Tester la connexion PDO
}
catch (\Exception $e)
{
Log::error('Failed to reconnect to the database: ' . $e->getMessage());
throw $e;
}
Log::info('Database connection successfully re-established: ' . DB::connection()->getDatabaseName());
}
And it works perfectly, BUT not with livewire.
Here is my livewire controller :
class MyLiveWireController extends Component
{
public $idCampaign;
public $campaign;
public function switchDatabase()
{
Log::info(__CLASS__ . ":" . __FUNCTION__);
if (Auth::check())
{
$user = Auth::user();
$userDatabase = "xbot_" . $user->bot_database;
Config::set('database.connections.mysql.database', $userDatabase);
DB::purge('mysql');
DB::reconnect('mysql');
try
{
$pdo = DB::connection('mysql')->getPdo(); // Tester la connexion PDO
}
catch (\Exception $e)
{
Log::error('Failed to reconnect to the database: ' . $e->getMessage());
throw $e;
}
}
Log::info("Database : " . DB::connection()->getDatabaseName());
}
public function mount($idCampaign)
{
Log::info(__CLASS__ . ":" . __FUNCTION__ . " idCampaign = " . $idCampaign);
$this->idCampaign = $idCampaign;
}
public function render()
{
Log::info(__CLASS__ . ":" . __FUNCTION__);
$this->switchDatabase();
$this->campaign = Campaign::find($this->idCampaign);
return view('livewire.my-table', []);
}
}
The livewire view :
<div wire:poll> Hello</div>
Every time the the render is called, I got :
livewire.js?id=38dc8241:4284 POST http://localhost:8000/livewire/update 404 (Not Found)
Please note that :
when I login with the admin user, which means the database is the same, the call of switchDatabase() does not cause any error.
if I remove the line $this->campaign = Campaign::find($this->idCampaign); it works.
Of course if I use array :
$campaignData = [
'id' => $campaign->id,
'name' => $campaign->name
];
return view('livewire.tweet-table', [
'campaign' => $campaignData,
]);
It works, but I really really would prefer to use eloquent collection or it will be nightmare...
Any ideas?
Thanks