Author - StudySection Post Views - 55 views
databases

How to Use Two Databases In a Single Project?

We will be discussing the usage of two databases (MySQL and MongoDB) in one project (Laravel).

  1. For multiple databases first of all, go to your .env file and set the following:


    DB_CONNECTION=mysql
    DB_HOST=localhost
    DB_PORT=3306
    DB_DATABASE=database1
    DB_USERNAME=root
    DB_PASSWORD=123456

    DB_CONNECTION_SECOND=mongodb
    MONGO_DB_HOST=localhost
    MONGO_DB_PORT=27017
    MONGO_DB_DATABASE=database2
    MONGO_DB_USERNAME=null
    MONGO_DB_PASSWORD=null

  2. After changes in .env file go to your config/database.php


    'mysql' => [
    'driver' => env('DB_CONNECTION'),
    'host' => env('DB_HOST'),
    'port' => env('DB_PORT'),
    'database' => env('DB_DATABASE'),
    'username' => env('DB_USERNAME'),
    'password' => env('DB_PASSWORD'),
    ],

    'mongodb' => [
    'driver' => 'mongodb',
    'host' => env('MONGO_DB_HOST', 'localhost'),
    'port' => env('MONGO_DB_PORT', 27017),
    'database' => env('MONGO_DB_DATABASE'),
    'username' => env('MONGO_DB_USERNAME'),
    'password' => env('MONGO_DB_PASSWORD'),
    'options' => [] ],

  3. When you are creating a migration use database like this


    public function up()
    {
    Schema::connection('mongodb')->create('table_name', function (Blueprint $table) {
    $table->increments('id');
    $table->string('user_name');
    $table->timestamps();
    });
    }

  4. If you are using eloquent then create a model and add these


    protected $connection = 'mongodb';
    protected $collection = 'table_name';

    In your class. Now you can use your model where you want to like you use your normal models.
    For example:

    $data = TableName:get()->toArray();

  5. If you are not using eloquent then use query builder like this

    $data = DB::connection('mysql2')->select(...);

jQuery presents a tree-like structure of all the elements on a webpage simplifying the syntax and further manipulating such elements. The jQuery Certification exam by StudySection will secure your fundamental knowledge and a basic understanding of jQuery as an asset to improve your skills.

Leave a Reply

Your email address will not be published. Required fields are marked *