Showing posts with label DB. Show all posts
Showing posts with label DB. Show all posts

Friday, June 30, 2017

Laravel 5: Change Default Database connection Dynamically | Change database name of connection on the fly | How to change default database connection in controller | Multiple DB Connections | Specifying DB connection information dynamically instead of config key | How to Use Multiple Database Connections in Laravel Application

use Illuminate\Config\Repository;

public function __construct(Repository $config) {}


So now you can $config from the above reference.

Below is a sample usage of change database name:

$config->set("database.connections.mysql.database", "test");

or

app()->config->set("database.connections.mysql.database", "test");

You can use this functionality in middle-ware.

If your app already connected then you have to disconnect it before make new connection available.

Below follow steps to disconnect connection:

$dm = app("Illuminate\\Database\\DatabaseManager");

$dm->disconnect();

Saturday, February 11, 2017

Laravel join or left join queries AS different name

There are many situations where you need to join same table, but must have different names (you can define this as alias). Below is a simple code snippet to show how you can join same table with different name.

$limit = 10;
$page = 1;
$groups = DB::table('person')
       ->leftJoin('users as for_user', function ($join) {
           $join->on('for_user.id', '=', 'person.for_id')->where("for_user.id", "=", 10);
       })
       ->join('users as by_user', function ($join) {
           $join->on('by_user.id', '=', 'person.by_id');
       })
       ->where('person.status', '=', 1)
       ->select('person.id', 'person.first_name', 'by_user.first_name')
       ->limit($limit)->offset($page * $limit)
       ->get();