Set connection according to logged-in user data

0

I created a second connection in my config / database.php file and I will also create a third one, I wanted to know how I can switch between these connections according to the logged in user.

config / database.php

'connections' => [

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

        'database2' => [
            'driver' => 'mysql',
            'host' => ('localhost'),
            'port' => ('3306'),
            'database' => ('database2'),
            'username' => ('root'),
            'password' => (''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

    ],

I know that I can choose the connection on my model in this way, but how do I get the name " database2 " to be pulled from the logged in user instead of being placed directly there? >

class Empresa extends Model
{
    protected $connection;

    function __construct()
    {
        return $this->connection = 'database2';
    }
}

I tried to put it that way, but it did not work.

return $this->connection = Auth::user()->database;

You gave this error.

  

ErrorException in Company.php line 16:

     

Trying to get property of non-object

    
asked by anonymous 30.09.2016 / 15:55

2 answers

1

I noticed that you are trying to access user data without verifying that it is authenticated or not. You must set a behavior if the user is not logged in.

The way you did it probably gave error because the user was not logged in. If you try to call the user's data before it is logged in, you will see the error Try to get a property of a non-object .

A problem with Laravel's Auth 5

Another thing still is that because web Middleware may not even have been executed at the time of the Auth::user() call. In this case, if the \Illuminate\Session\Middleware\StartSession::class middleware is not executed (and it is within the web group, the Auth::user() data will not be loaded because the middleware would be processed after processing the route.

Then two things: If you need to process Authentication data elsewhere in the application (like in Service Provider for example), it would be interesting to make the following change:

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,

    // Pequena alteração. Inicialização de cookies, sessão e erros devem ser incluídos o quanto antes, por contas das requisições que retornam erros

    \Tmt\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
];

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        // \Tmt\Http\Middleware\EncryptCookies::class,
        // \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        // \Illuminate\Session\Middleware\StartSession::class,
        //\Illuminate\View\Middleware\ShareErrorsFromSession::class,

        \Tmt\Http\Middleware\VerifyCsrfToken::class,
    ],

    'api' => [
        'throttle:60,1',

Solution

The main lesson I would like to explain in this answer is this: It would be interesting to create a Middleware to define the default connection according to the user:

public function handle($request, Closure $next) {

    auth()->check() && config(['database.default' => auth()->user()->database]);

    return $next($request);
}
    
30.09.2016 / 18:51
0

The initial logic would be, users ( user ) would have a configured default connection . After user authentication, create instances of the classes that they inherit from Eloquent ( os models ) as follows:

Controller

namespace App\Http\Controllers;

class CreditosController extends Controller 
{
    private $credito;
    public function __construct()
    {
        // pode fazer injeção pelo construtor também ...
        $this->credito = new App\Models\Creditos(); 

        $this->credito->setConnection(Auth::user()->database);
    }
}

Change the connection of this model . The process would be done in Controller , yes and maybe straight, but I would not recommend it.

30.09.2016 / 16:32