0
votes

In my project every user has his/her database and I have defined the connection on config/database.php. So, in the model need to set the database connection.

// defines default database connection
protected $connection = Auth::user()->database;

I can't use this because it will throw an error: Constant expression contains invalid operations

Can anyone help me with this please?

To store and show data, I use:

DB::connection(Auth::user()->database)->table(...

And works like a charm. Can someone help me with $connection to be ble to set it by a variable?

Regards

1
Can you set $this->connection = Auth::user()->database in your constructor?Jeremy Harris
Beware you might get into trouble when no user is logged in when querying.Jerodev
@JeremyHarris, inside the controller, if I define __construct() with Auth::, gives error -- Trying to get property 'database' of non-object.hmrneves
@Jerodev, the app ad every route protected by auth middleware, so, shouldn't be a problem ;) thanks!hmrneves
How about your login route?Jerodev

1 Answers

0
votes

Solved the problem via middleware.

public function handle($request, Closure $next, $database)
{
    // check witch database connection to use
    switch ($database) {
        case 'self':
            // Set the User Database Connection
            DB::setDefaultConnection(Auth::user()->database);
            // Reconnect
            DB::reconnect();
            break;
        case 'main_db':
            // Set the User Database Connection
            DB::setDefaultConnection('main_db');
            // Reconnect
            DB::reconnect();
            break;
        default:
            // default action
            abort(403, 'Não está autorizado a aceder ao recurso solicitado.');
            break;
    }
    // next request...
    return $next($request);
}

And, in every controller:

public function __construct()
{
    // calls the middleware: SetDatabaseConnection
    $this->middleware('SetDatabaseConnection:self');
}

Thanks for the tips.