Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

veptune's avatar

I got livewire/update 404 (Not Found) when I switch database in the Livewire controller

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 :

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 :

  1. when I login with the admin user, which means the database is the same, the call of switchDatabase() does not cause any error.

  2. 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

0 likes
0 replies

Please or to participate in this conversation.