Skip to content

Instantly share code, notes, and snippets.

@jaygaha
Created June 8, 2024 06:34
Show Gist options
  • Save jaygaha/ea3a1c8a6bb72657ff697907df13b0be to your computer and use it in GitHub Desktop.
Save jaygaha/ea3a1c8a6bb72657ff697907df13b0be to your computer and use it in GitHub Desktop.
Override Model connections in Laravel for unit testing

Override Model connections in Laravel for unit testing

If you have specified a different connection that should be used when interacting with a particular model.

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Flight extends Model
{
    /**
     * The database connection that should be used by the model.
     *
     * @var string
     */
    protected $connection = 'mysql_2';
}

While doing unit tests you may have encountered a connection errors or have to defined multiple databases. If you want to use single database for the unit tests. It can be overrides from the Model.

<?php

	/**
	 * Get the database connection for the model.
	 *
	 * @return string
	 */
	public function getConnectionName()
	{
	    // Set the connection based on the environment
	    if (app()->environment('testing')) {
	        return 'mysql';
	    }

	    // Default to the application's default connection
	    return $this->connection;
	}

Now while running unit tests, it will use the default database.

#gist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment