Search code examples
laraveldatabaselaravel-5laravel-artisantinker

How to specify Tinker to use a different database connection?


I have two database connections. One for my application and another for testing. In my ..\config\database.php

         'mysql' => [
            'driver'    => 'mysql',
            'host'      => env('DB_HOST', 'localhost'),
            'database'  => env('DB_DATABASE', 'forge'),
            'username'  => env('DB_USERNAME', 'forge'),
            'password'  => env('DB_PASSWORD', ''),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],

        'testing' => [
            'driver'    => 'mysql',
            'host'      => env('DB_TEST_HOST', 'localhost'),
            'database'  => env('DB_TEST_DATABASE', 'forge'),
            'username'  => env('DB_TEST_USERNAME', 'forge'),
            'password'  => env('DB_TEST_PASSWORD', ''),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],

I am able to change the database connection in seeding using

php artisan db:seed --database=testing

I wanted to use tinker for the connection 'testing' but unable to change it. Is there any way to change the database connection for tinker similar with database seeding?


Solution

  • As your question starts with using one database for testing/development and one for production, you should look into using different environments, this will allow you to have no change in your code between deployment & local testing.


    This task can easily be achieved by specifying your environment:

    php artisan tinker --env=local
    

    By default, if you specify no --env, you will be using /your-app/.env

    When using local you read variables from /your-app/.env.local


    For your specific use case:

    php artisan db:seed --env=local
    

    Further reading for Laravel 5.1: https://laravel.com/docs/5.1/configuration

    Latest version: https://laravel.com/docs/configuration

    NB: You should avoid checking in the ".env" file to VCS, the .env.local should be OK to share, but it is best practice to not bundle production credentials with your VCS.