Laravel tests database migration from schema - php

The problem
I am using Laravel 8.83.23
I have schema dump from squashed migrations in database\schema\mysql-schema.dump
tests are running above test database, as in database.php
'testing' => [
'driver' => 'mysql',
'host' => env('DB_TEST_HOST', '127.0.0.1'),
'port' => env('DB_TEST_PORT', '3306'),
'database' => env('DB_TEST_DATABASE', 'forge'),
'username' => env('DB_TEST_USERNAME', 'forge'),
'password' => env('DB_TEST_PASSWORD', ''),
],
Before I squashed migrations, my test cases only used DatabaseMigrations trait, and the test database was recreated every time and all worked, example of test class:
class SystemControllerTest extends TestCase
{
use WithFaker;
use DatabaseMigrations;
/**
* #var User
*/
private $user;
public function setUp(): void
{
parent::setUp();
//create roles and data
$this->seed(RoleAndPermissionSeeder::class);
... etc
the migrations were found and executed, recreating the database
then, I squashed the migrations, so all migrations got deleted, and I got database\schema\mysql-schema.dump
php artisan migrate works as expected through command line, creating full database schemas from the dump (it finds it)
tests however no longer work, as there is an error
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'cinema_test.roles' doesn't exist (SQL: delete from `roles`)
when I check the sql test database after the test runs, it is empty (only table migrations gets created there, and it is empty)
this error persists even when I call artisan migrate in the test's setup:
public function setUp(): void
{
parent::setUp();
Artisan::call('migrate', array(
'--database' => 'testing',
'--force' => true));
//it crashes here
$this->seed(RoleAndPermissionSeeder::class);
RoleAndPermissionSeeder just operates with the sql tables, which do not exist, hence the error
I even tried DatabaseMigrations and DatabaseTransactions and RefreshDatabase traits, without any success
how do I populate the database data? There is no way for me to read the output of the Artisan::call('migrate') command, so I do not know what is happening there
return code of Artisan::call('migrate') is 0
is there maybe some setup I am missing?

I have finally figured this out.
The reason for the problem
The problem was in incorrect setup of the testing environment. I have not discovered the exact reason, but I figured out how to setup the testing environment so that the dump would be found and loaded.
How I hunt down the bug
This describes my steps on how I found a way to fix this.
In database.php I have copied testing database instead of normal one
in database.php I had the main database connection:
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => false,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
and the testing connection
'testing' => [
'driver' => 'mysql',
'host' => env('DB_TEST_HOST', '127.0.0.1'),
'port' => env('DB_TEST_PORT', '3306'),
'database' => env('DB_TEST_DATABASE', 'forge'),
'username' => env('DB_TEST_USERNAME', 'forge'),
'password' => env('DB_TEST_PASSWORD', ''),
],
I copied the testing connection data into a new mysql connection, just to see, whether on a command line I get same results
so, the file then looked like this
'mysql' => [
'url' => env('DATABASE_URL'),
'driver' => 'mysql',
'host' => env('DB_TEST_HOST', '127.0.0.1'),
'port' => env('DB_TEST_PORT', '3306'),
'database' => env('DB_TEST_DATABASE', 'forge'),
'username' => env('DB_TEST_USERNAME', 'forge'),
'password' => env('DB_TEST_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => false,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
/*'testing' => [
'driver' => 'mysql',
'host' => env('DB_TEST_HOST', '127.0.0.1'),
'port' => env('DB_TEST_PORT', '3306'),
'database' => env('DB_TEST_DATABASE', 'forge'),
'username' => env('DB_TEST_USERNAME', 'forge'),
'password' => env('DB_TEST_PASSWORD', ''),
],*/
on the console, I ran php artisan:migrate
the database dump was found and loaded
therefore, the dump was found in normal cases, but was not found, in testing cases
after some research, I changed the testing environment setup in phpunit.xml, I will explain it now
The file phpunit.xml
The phpunit.xml was as follows (not full file shown here):
<server name="QUEUE_CONNECTION" value="sync"/>
<server name="SESSION_DRIVER" value="array"/>
<server name="TELESCOPE_ENABLED" value="false"/>
<env name="DB_CONNECTION" value="testing"/>
</php>
</phpunit>
so, we can see that the testing database connection is defined for unit tests
on web I found advice to set the database table only, instead of changing entire connection for tests, because it is easier
I tried such an approach, so the phpunit.xml became
<server name="QUEUE_CONNECTION" value="sync"/>
<server name="SESSION_DRIVER" value="array"/>
<server name="TELESCOPE_ENABLED" value="false"/>
<env name="DB_DATABASE" value="cinema_test"/>
</php>
</phpunit>
I deleted the testing connection from database.php and related obsolete variables from .env file
this fixed the issue, and the dump file got loaded even in tests now
Conclusion
Although I have not figured out the real cause for the lavavel not loading the dump file, I have found a workaround which was to only change the database name for tests, instead of defining entirely new sql connection for testing pursposes. This solved the issue, and the database dump file gets loaded during tests now.

Seems like schema dumps can't be used for the in-memory database when testing
https://laravel.com/docs/9.x/migrations#squashing-migrations
May be able to do something like this
DB::unprepared(file_get_contents("path/file.sql"));
Would only try as a last resort, personally would want a test environment migration, also you should add a check for a test environment migration if you take this approach

Related

Laravel won't connect to MySQL8 (AWS RDS)

I have updated a Laravel 5.5-installation to 5.8 and am now attempting to update the MySQL-installation from 5.7 to 8.0.19. The Laravel-installation is on an EC2-instance and works great with the previous RDS MySQL/Aurora installation, but the version did not cut it.
We are running this on an nginx-server.
First I got an error-message stating
(2/2) PDOException
SQLSTATE[HY000] [2002] Connection refused
Tried to change the AWS uri and use the ip instead, and got a 504 instead.
I tried to access the database through MySQL Workbench and through new PDO('mysql:host=xx-rds-staging-mysql-8.xxxxxxxxxxxx.eu-west-1.rds.amazonaws.com;port=3306;dbname=database', 'username', 'password', [0, 2, 0, false, false, false]) and... they both work perfectly from the EC2-instance.
Env-file:
DB_CONNECTION="mysql"
DB_HOST_WRITE="xx-rds-staging-mysql-8.xxxxxxxxxxxx.eu-west-1.rds.amazonaws.com"
DB_HOST_READ="xx-rds-staging-mysql-8.xxxxxxxxxxxx.eu-west-1.rds.amazonaws.com"
DB_PORT_READ_AND_WRITE="3306"
DB_DATABASE="database"
DB_USERNAME="username"
DB_PASSWORD="password"
config/database.php
'mysql' => [
'read' => [
'host' => env('DB_HOST_READ', '127.0.0.1'),
],
'write' => [
'host' => env('DB_HOST_WRITE', '127.0.0.1'),
],
'port' => env('DB_PORT_READ_AND_WRITE', '3306'),
'driver' => 'mysql',
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
'sticky' => true,
'version' => 8,
'modes' => [
#'ONLY_FULL_GROUP_BY',
'STRICT_TRANS_TABLES',
'NO_ZERO_IN_DATE',
'NO_ZERO_DATE',
'ERROR_FOR_DIVISION_BY_ZERO',
'NO_ENGINE_SUBSTITUTION',
],
'options' => [
PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT => false,
],
],
I have cleared the cache by all the artisan-commands and by deleting the cache-folder.
I am rubbish at asking for help here, not ever certain what information I need to share to make my case.
My first thought is that there ought to be some setting in Laravel which I could swap to make this work, but I have no idea what it could be.
The mysql-server does not run on the same machine as the laravel-application and AWS has not offered a public ip, just the uri.
What makes it even stranger is that I can enter php artisan tinker and run, for example, User::first(); and it will fetch the appropriate row from the database, without any issue.
No details informaton but you can review below points:
Verify your Laravel/php config or connection file didn't change and have same settings as before.
Did you set any zone specific resstriction in RDS? Does your testing environment complies it?

How to setup Laravel using a shared host with sqlsrv?

I have a project developed in Laravel and I want to upload the project to a Linux shared hosting.
In my project I have 2 connection to different database. First is mysql database that is in shared hosting and works well. Second is an sql server database that access to another server. So for that second database I use sqlsrv driver but I having problems to put this working at linux shared hosting, returns me this error:
SQLSTATE[HY000] Unable to connect: Adaptive Server is unavailable or does not exist (severity 9)
at PDO->__construct('dblib:host=IP:1433;dbname=DBNAME;charset=utf8', 'USER', 'PASSWORD', array(0, 2, 0, false))
I set the connection like this:
'DB2' => [
'driver' => 'sqlsrv',
'host' => env('DB_HOST', 'IP'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'DBNAME'),
'username' => env('DB_USERNAME', 'USER'),
'password' => env('DB_PASSWORD', 'PASSWORD'),
'charset' => 'utf8',
'prefix' => '',
],
Before this error I have a lot of another errors because this connection, so I have to add some extensions to php and update to 7.2 version. I also add some PHP pear packages .
The next image show you the extensions that I add:
In my local machine I can run the project without any problem and both connection working fine.
How can I solve that?
You should define DB_HOST and DB_PORT environment variables inside .env file for sqlsrv driver. Currently, it looks like the default values are used for the connection. (Default value - is the second parameter of env() function).
P.S. Please note, if you use two different connection - variable names should be different, for example:
.env content:
...
MYSQL_DB_HOST=0.0.0.0
MYSQL_DB_PORT=3939
SQLSRV_DB_HOST=0.0.0.0
SQLSRV_DB_PORT=1433
...
config/database.php content:
...
'DB' => [
'driver' => 'mysql',
'host' => env('MYSQL_DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3939'),
'database' => env('DB_DATABASE', 'DBNAME'),
'username' => env('DB_USERNAME', 'USER'),
'password' => env('DB_PASSWORD', 'PASSWORD'),
'charset' => 'utf8',
'prefix' => '',
],
'DB2' => [
'driver' => 'sqlsrv',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'DBNAME'),
'username' => env('DB_USERNAME', 'USER'),
'password' => env('DB_PASSWORD', 'PASSWORD'),
'charset' => 'utf8',
'prefix' => '',
],
...
I think first of all check your hosting server php version and try to put correct PDO driver for PHP version.
if you use a PHP Version 7.1.7 for *86 Architecture then put that .dll file.
extension=php_pdo_sqlsrv_71_ts_*86.dll
and if you use another Version of PHP then try to put a correct .dll file and also declare into php.ini file.
and restart your service and run it...
I hope it would help you...

Laravel Rollback specific database

I try to rollback my database system with
php artisan migrate:rollback --database='system'
but it seem the doen't work like the migreation php artisan migrate --database='system
can't you help me found what going on.
here my config/database.php
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
],
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '4444'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
'system' => [
'driver' => 'mysql',
'host' => env('SYSTEM_DB_HOST', 'localhost'),
'port' => env('SYSTEM_DB_PORT', '4444'),
'database' => env('SYSTEM_DB_DATABASE', 'forge'),
'username' => env('SYSTEM_DB_USERNAME', 'forge'),
'password' => env('SYSTEM_DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
this is my .env file.
#-----------------------------------------------------
# CLIENT DB CONNECTION
#-----------------------------------------------------
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=databaseNameClient
DB_USERNAME=homestead
DB_PASSWORD=secret
#-----------------------------------------------------
# SYSTEM DB CONNECTION
#-----------------------------------------------------
DB_CONNECTION=system
SYSTEM_DB_HOST=127.0.0.1
SYSTEM_DB_PORT=3306
SYSTEM_DB_DATABASE=databaseNameSystem
SYSTEM_DB_USERNAME=homestead
SYSTEM_DB_PASSWORD=secret
this is the message error i got when i try migration:rollback --database='system' :
[Symfony\Component\Debug\Exception\FatalThrowableError]
Call to undefined method Illuminate\Database\Schema\MySqlBuilder::dddconnection()
the last lines for my stack trace are:
#23 /vendor/symfony/console/Application.php(117): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#24 /vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(107): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#25 /artisan(35): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#26 {main}
[2018-04-17 00:51:07] local.ERROR: Symfony\Component\Debug\Exception\FatalThrowableError: Call to undefined method Illuminate\Database\Schema\MySqlBuilder::dddconnection() in /vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:217
You have accidently changed the methods in vendor folder.
Step 1.
delete the vendor folder.
Step 2.
run
composer install
It will install all the libraries again and overwrite changes.
Hope this helps
It's quite difficult to say without looking at full error log, but there is alternate for this, if you create down methods for your migration by providing specific database connection like this
Schema::connection('mysql2')->create('some_table', function($table)
{
$table->increments('id'):
});
Then only php artisan migrate:rollback will work perfectly for this.
If you look in your migrations table, then you’ll see each migration
has a batch number. So when you roll back, it rolls back each
migration that was part of the last batch.
If you only want to roll back the very last migration, then just
increment the batch number by one. Then next time you run the rollback
command, it’ll only roll back that one migration as it’s in a “batch” of
its own.
for more follow the url :
Rollback one specific migration in Laravel
Hi thanks your all to take your time to answered my question. I found what going on. In one ove my migration, in the down function I have a function was misspelled
public function down()
{
if (Schema::dddconnection('system')->hasTable('apiservices_categories_translations')) {
Schema::connection('system')->dropIfExists('apiservices_categories_translations');
}
}

Laravel multiple databases PHPUnit [duplicate]

This question already has answers here:
How to use multiple databases in Laravel
(7 answers)
Closed 5 years ago.
I am developing a application with multiple database access and I want to have PHPUnit tests with this. My current approache is to have in the config\databases.php multiple connections (mysql, mysql2, mysql3) so I can have in the env file a different access for all of them. Because of this, the models have the $connection variable defined. In my first feature test I want to access a page and just see the data that I am providing in my factory, so just to get things started. In my phpunit.xml file I have specified the DB_CONNECTION to be sqlite and for each of the MySql setting to have the value=":memory:".
LATER EDIT
<php>
<env name="APP_ENV" value="testing"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="QUEUE_DRIVER" value="sync"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE_1" value=":memory:"/>
<env name="DB_DATABASE_2" value=":memory:"/>
<env name="DB_DATABASE_3" value=":memory:"/>
</php>
So above you can find the relevant code from PHPUnit.
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db1
DB_USERNAME=xxx
DB_PASSWORD=xxx
DB_HOST_2=127.0.0.1
DB_PORT_2=3306
DB_DATABASE_2=db2
DB_USERNAME_2=xxx
DB_PASSWORD_2=xxx
DB_HOST_2=127.0.0.1
DB_PORT_2=3306
DB_DATABASE_3=db3
DB_USERNAME_3=xxx
DB_PASSWORD_3=xxx
The problem that I have is the fact that when I run the tests, i have this error -> PDOException: SQLSTATE[HY000] [1049] Unknown database ':memory:'.
So somehow Laravel is not parsing the memory value. Any suggestion will be mush appreciated.
Thank you
I was having the same issue, but I got things working with some help from Adam Wathan on Twitter.
Here's what I did:
phpunit.xml:
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
<env name="DB_CONNECTION_ACTIVITY_LOG" value="sqlite"/>
<env name="DB_DATABASE_ACTIVITY_LOG" value=":memory:"/>
config/database.php:
'sqlite' => [
'driver' => 'sqlite',
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
],
'mysql' => [
'driver' => env('DB_CONNECTION', 'mysql'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
'mysql-activity-log' => [
'driver' => env('DB_CONNECTION_ACTIVITY_LOG', 'mysql'),
'host' => env('DB_HOST_ACTIVITY_LOG', '127.0.0.1'),
'port' => env('DB_PORT_ACTIVITY_LOG', '3306'),
'database' => env('DB_DATABASE_ACTIVITY_LOG', 'forge'),
'username' => env('DB_USERNAME_ACTIVITY_LOG', 'forge'),
'password' => env('DB_PASSWORD_ACTIVITY_LOG', ''),
'unix_socket' => env('DB_SOCKET_ACTIVITY_LOG', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
.env:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=my-app
DB_USERNAME=root
DB_PASSWORD=
DB_CONNECTION_ACTIVITY_LOG=mysql-activity-log
DB_HOST_ACTIVITY_LOG=127.0.0.1
DB_PORT_ACTIVITY_LOG=3306
DB_DATABASE_ACTIVITY_LOG=my-app
DB_USERNAME_ACTIVITY_LOG=root
DB_PASSWORD_ACTIVITY_LOG=
Also, for anyone not up to the point of the PDOException, make sure to set the connections in your migrations/models, too.
database/migrations/my_migration.php:
Schema::connection(env('DB_CONNECTION_ACTIVITY_LOG', 'mysql'))->create(...);
app/MyModel.php:
class MyModel extends Model
{
public function __construct($attributes = [])
{
parent::__construct($attributes);
$this->connection = config('app.env') === 'testing' ? 'sqlite' : 'mysql-activity-log';
}
...
}
Hard to decode where you actually put the :memory: value.
In the phpunit.xml <php> section, this should be sufficient (assuming you haven't modified the sqlite connection):
<php>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
</php>
To resolve a similar problem, I used a trait on the Model classes.
In my phpunit.xml I have this code
<env name="DB_CONNECTION" value="sqlite_testing"/>
<env name="DB_DATABASE" value=":memory:"/>```
In my config/database.php file I have connections set up for each of the databases, and a sqlite_testing connection set up for testing
'sqlite_testing' => [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
],
'mysql_connection_a' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
'mysql_connection_b' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE_B', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
'mysql_connection_c' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE_C', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
I then create a trait for each of my connections to set the connection and include them in the relevant models. e.g. if the User model needed to use mysql_connection_a I would use ConnectionATrait in the model
use App\Traits\ConnectionATrait;
class User extends Authenticatable
{
use Notifiable, ConnectionATrait;
The trait would then look like this
trait ConnectionATrait
{
/**
* The database table used by the model.
*
* #var string
*/
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
if (env('APP_ENV') != 'testing') {
$this->connection = 'mysql_connection_a';
}else{
$this->connection = 'sqlite_testing';
}
}
}
If you use migrations in your tests I also had to do a similar approach in the migration files and use a trait for each connection.
For the mysql_connection_a I create a trait that looks likes below that overrides the getConnection method:
trait ConnectionAConnectionTrait
{
/**
* Get the migration connection name.
*
* #return string
*/
public function getConnection()
{
if (env('APP_ENV') != 'testing') {
return 'mysql_connection_a';
}
return 'sqlite_testing';
}
}
Then in the migration it would look like this
use Database\migrations\traits\ConnectionAConnectionTrait;
class CreateUsersTable extends Migration {
use ConnectionAConnectionTrait;
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::connection($this->getConnection())
->create('users', function(Blueprint $table)
{

Laravel testing with phpunit

How can I make sure that when I'm testing in Laravel with phpunit and for example I want to test my api route /test/1 it uses my test database?
I already made a test connection and changed my phpunit.xml file. I changed DB_CONNECTION to the test connection that I made.
<env name="DB_CONNECTION" value="mysql_testing"/>
But it when I make a post request I receive data from the development database?
In your Config/database.php file, what is the value of database in mysql_testing? It should be like this:
'mysql_testing' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
'database' => env('TEST_DB_DATABASE', 'db_testing'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
And database db_testing must exists.
Inside one of your test files, add the following to output your current DB_CONNECTION:
dd(env('DB_CONNECTION'));
You should get mysql_testing in your test output if PHPUnit.xml is properly setup.

Categories