vendredi 30 novembre 2018

Unable to connect with database with manual settings in laravel

The project were I'm working needs connect with multiple databases on runtime to this, I'm setting the connection propertie on the fly, I'm doing this as follows:

I create a helpers

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

if(! function_exists('conexionBD')){

    /**
     * Establish a tenant database connection.
     *
     * @param $hostname
     * @param $username
     * @param $password
     * @param $database
     */

    function conexionBD($hostname, $username, $password, $database){
        DB::purge('empresa');

        Config::set('database.connections.empresa.host', $hostname);
        Config::set('database.connections.empresa.database', $database);
        Config::set('database.connections.empresa.username', $username);
        Config::set('database.connections.empresa.password', $password);

        DB::reconnect('empresa');

        Schema::connection('empresa')->getConnection()->reconnect();
    }
}

I created a Middleware called Tenant

public function handle($request, Closure $next) {
        if (($request->session()->get('empresaId')) === null)
            return redirect()->route('inicio')->withErrors(['error' => __('Por favor inicie sesión en alguna empresa antes de intentar esta acción')]);

        $empresa = new empresa();
        $empresa->connect();

        return $next($request);
    }

My model of empresa is like that

class empresa extends Model
{
    protected $fillable = [
        'hostname',
        'username',
        'password',
        'database'
    ];

    public function connect()
    {
        if (! $this->connected()) {
            conexionBD(
                $this->hostname,
                $this->username,
                $this->password,
                $this->database
            );
        }
    }

    private function connected()
    {
            $connection = Config::get('database.connections.empresa');
            return $connection['username'] == $this->username &&
            $connection['password'] == $this->password &&
            $connection['database'] == $this->database;
    }
}

Now, when I run this code, I get "SQLSTATE[HY000] [1045] Access denied for user ''@'localhost' (using password: NO)" error, in my database config I have the database, username, password and host empty. In my database, in the empresas table I have that fields with correct information, but at the moment of change the database, the system tell me that, and I don't understand why if I'm not have a localhost user and my database has a password

Someone knows that my code is missing or that I am doing wrong to make the multi-tenant system work correctly?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2Pal0BN
via IFTTT

Aucun commentaire:

Enregistrer un commentaire