Set database for model? - laravel

I'm working on a Laravel 4 based site which works over multiple databases. There is one query I need to run on each request that pulls a record from a different database.
Is there a way I can somehow tie this particular model to the other database so I can just retrieve it as usual?
$client = Client::find(Session::get('client_id'));
Any advice appreciated.
Thanks

// Model
class Client extends Eloquent
{
protected $connection = 'masterDb';
}
// config/database.php
'masterDb' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'name',
'username' => 'user',
'password' => 'pass',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
You can create as many named connections as you wish. Set one of them as default,
each model can use any of these connections later.

Related

Change database connection when using Laravel Auth

In a multi-tenant Laravel app, each tenant has its own database connection. So after the user has selected his database, I want to authenticate the user using Auth::loginUsingId. Still, no matter what I do, I cannot change the Users Model's connection to another default.
If I set the connection in the model, it does connect to the specific database, but I want this to be done dynamically.
Is there a way to specify the connection dynamically that Laravel's auth should use for the authentication?
You could define another connection in your config/database.php file like this:
return array(
'connections' => array(
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database1',
'username' => 'user1',
'password' => 'pass1'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
'second_db_connection' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database2',
'username' => 'user2',
'password' => 'pass2'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
)
And change the User model to be like this:
class User extends Model {
protected $connection = 'second_db_connection';
}
Before authenticating the user, change the database connection temporarily for the current request only using Conifg::set
$db = "database_name";
Config::set("database.connections.mysql.database", $db);

LARAVEL Eloquent query multiple schema

Do i need to create multiple connection to access different database/schema. Cant I use with one dbconnection. Is there a way to pass the database name in the laravel eloquent or db builder? Currently in raw php i use one connection to query the different schema.
Create different connections to your database.php file and then pass them to your eloquent models.
'mysql1' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => 'db1',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
// connection 2
'mysql2' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => 'db2',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
Suppose i have model User.php uses mysql connection named mysql1
inside my model i will add :
protected $connection = 'mysql1';
if i want to use mysql connection named mysql2
then i will use
protected $connection = 'mysql2';
Here i am setting connections statically in to models.
In Eloquent, I use DB:connection() to set my named connection, like so:
$query = DB::connection('db_connection_name')->table($this->table)
If you weren't aware, the database connections are named in the config app/config/database.php

Orchestral/tenanti multi database

I build an application for many tenants and each tenant has it's own database. The name of the database is the same as the tenants id.(the id exists out of five numbers). After authentication the user should be connected with his own database and redirected to his dashboard.
I tried to connect the user with his database with the following code, which I placed in Authenticate.php
if (!Auth::guest() && Auth::user()->tenant) {
$user = Auth::id();
Tenanti::driver('user')->asDefaultDatabase($user, 'users_{id}');
Config::set('database.connections.mysql.database', 'user_'.$user);
}
The if statement checks in the main database if the logged in user is a tenant(boolean).
The config/database.php contains the following code:
'tenants' => [
'user_1' => [
'driver' => 'mysql',
'host' => 'localhost', // for user with id=1
'database' => '86097', // for user with id=1
'username' => 'root', // for user with id=1
'password' => 'root', // for user with id=1
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
],
AppServiceProvider:
<?php namespace App\Providers;
use Orchestra\Support\Facades\Tenanti;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Tenanti::setupMultiDatabase('tenants', function (User $entity, array $template) {
$template['database'] = "user_{$entity->getKey()}";
return $template;
});
}
}
?>
I don't get an error, but the connection hasn't changed. The user database is empty and therefore I shouldn't see any data when I log in with user_id=1 . Thanks in advance for helping.
The configuration should be:
'tenants' => [
'driver' => 'mysql',
'host' => 'localhost', // for user with id=1
'database' => '86097', // for user with id=1
'username' => 'root', // for user with id=1
'password' => 'root', // for user with id=1
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
Other than that please replace Tenanti::setupMultiDatabase() with Tenanti::connection() (we have deprecated the old method).
And change the following:
Tenanti::driver('user')->asDefaultConnection(Auth::user(), 'tenants_{id}');
Obviously if you want to use users_{id} you would then need to replace all tenants to users.

Laravel define database in model

A chunk of my SQL is held in a different database to the rest of my Laravel installation.
When I use a particular Model, how do I define in that Model, that I'd like to use a particular database and not the one defined in config/database.php?
I am using Laravel 5 so needs to be relevant to that version.
Update: Here is my model;
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Lookup extends Model {
protected $connection = 'postcodes';
}
Here is part of my config/database.php;
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', $_ENV["DB_HOST"]),
'database' => env('DB_DATABASE', $_ENV["DB_DATABASE"]),
'username' => env('DB_USERNAME', $_ENV["DB_USERNAME"]),
'password' => env('DB_PASSWORD', $_ENV["DB_PASSWORD"]),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
'postcodes' => [
'driver' => 'mysql',
'host' => env('DB_HOST', $_ENV["DB_HOST"]),
'database' => env('DB_DATABASE', 'postcodes'),
'username' => env('DB_USERNAME', $_ENV["DB_USERNAME"]),
'password' => env('DB_PASSWORD', $_ENV["DB_PASSWORD"]),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
It's not working - and I can't get Whooops errors to work so all I get is a white screen (but that's a separate issue).
I know my controller code is correct because when I temporarily copy the table in to my main Laravel database, it all works fine. So what's the issue?
You can define protected $connection = 'yourohterconnection'; in your model, and add another connection to your database config file.
I asked the same question on the Laravel forum and the posted solution worked for me.
Basically the problem is this line;
'database' => env('DB_DATABASE', $_ENV["DB_DATABASE_TWO"]),
Or in my code above at the time of writing it was actually;
'database' => env('DB_DATABASE', 'postcodes'),
It needs to be;
'database' => env('DB_DATABASE_TWO', $_ENV["DB_DATABASE_TWO"]),
And then your .env file needs to have DB_DATABASE_TWO=postcodes (or whatever the name of your second database is).

Laravel using different connections for Inserting & Selecting data

Is there anyway in the Laravel Eloquent to use two different connections, for inserting, updating and Selecting.
What i am trying to do is specify a connection when user is pulling the data from db, and another one while inserting or updating data.
I am wondering if it can be done with the Eloquent instead of defining connections everytime?
This is possible with Laravel 4.1. You can configure it in your app/config/database.php like so:
'mysql' => array(
'read' => array(
'host' => '192.168.1.1',
),
'write' => array(
'host' => '196.168.1.2'
),
'driver' => 'mysql',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
See the Read / Write Connections section in the Laravel database documentation.

Resources