search
HomePHP FrameworkLaravelHow to connect two databases to query data in laravel

With the continuous advancement and development of network technology, modern Web applications have become an indispensable part today. However, in Web applications, data management is obviously also a crucial link. Furthermore, for large web applications, there are usually multiple databases. For example, an e-commerce platform, in addition to the basic product information database, will also have different databases such as user information, order information, payment information, etc. So, how to connect multiple databases and query data under the Laravel framework? This article will provide a method that can be followed.

First, you need to configure multiple databases in Laravel's database configuration file config/database.php, as shown below:

'connections' => [

    'mysql' => [
        //mysql主数据库
        'driver' => 'mysql',
        'host' => 'localhost',
        'database' => 'db1',
        'username' => 'root',
        'password' => '',
    ],

    'mysql2' => [
        //mysql2次数据库
        'driver' => 'mysql',
        'host' => 'localhost',
        'database' => 'db2',
        'username' => 'root',
        'password' => '',
    ],

],

Two database connections, mysql and mysql2, are defined in the above configuration file. . The specific configuration can be adjusted according to your own needs.

Next, two database connections need to be defined. You can create a new base class ModelBase in the /model directory and define multiple connections in it.

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ModelBase extends Model
{
    // mysql
    protected $connection = &#39;mysql&#39;;

    // mysql2
    protected $connection2 = &#39;mysql2&#39;;

    protected function getConnectionName()
    {
        if ($this->getConnection() === $this->connection2) {
            return $this->connection2;
        }
        return $this->connection;
    }

    public function getTable()
    {
        $table = parent::getTable();

        if ($this->getConnection() === $this->connection2) {
            $table = 'db2.' . $table;
        }
        return $table;
    }

}

The above code defines two connections: mysql and mysql2. And, define the two functions getConnectionName and getTable. The getConnectionName function returns the current database connection name, and the getTable function is used to obtain the current database table.

Finally, use in the actual Model:

namespace App\Models;
class UserModel extends ModelBase
{
    protected $table = 'user';
}

In the Model, inherit from ModelBase, and when defining $table, you only need to write the table name.

The above is a method to connect two databases to query data in Laravel. In this way, query operations of multiple databases can be realized. For large-scale applications, this method can effectively solve query problems between multiple databases, making the program run more efficiently and stably.

The above is the detailed content of How to connect two databases to query data in laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to Use Laravel Migrations: A Step-by-Step TutorialHow to Use Laravel Migrations: A Step-by-Step TutorialMay 13, 2025 am 12:15 AM

LaravelmigrationsstreamlinedatabasemanagementbyallowingschemachangestobedefinedinPHPcode,whichcanbeversion-controlledandshared.Here'showtousethem:1)Createmigrationclassestodefineoperationslikecreatingormodifyingtables.2)Usethe'phpartisanmigrate'comma

Finding the Latest Laravel Version: A Quick and Easy GuideFinding the Latest Laravel Version: A Quick and Easy GuideMay 13, 2025 am 12:13 AM

To find the latest version of Laravel, you can visit the official website laravel.com and click the "Docs" button in the upper right corner, or use the Composer command "composershowlaravel/framework|grepversions". Staying updated can help improve project security and performance, but the impact on existing projects needs to be considered.

Staying Updated with Laravel: Benefits of Using the Latest VersionStaying Updated with Laravel: Benefits of Using the Latest VersionMay 13, 2025 am 12:08 AM

YoushouldupdatetothelatestLaravelversionforperformanceimprovements,enhancedsecurity,newfeatures,bettercommunitysupport,andlong-termmaintenance.1)Performance:Laravel9'sEloquentORMoptimizationsenhanceapplicationspeed.2)Security:Laravel8introducedbetter

Laravel: I messed up my migration, what can I do?Laravel: I messed up my migration, what can I do?May 13, 2025 am 12:06 AM

WhenyoumessupamigrationinLaravel,youcan:1)Rollbackthemigrationusing'phpartisanmigrate:rollback'ifit'sthelastone,or'phpartisanmigrate:reset'forall;2)Createanewmigrationtocorrecterrorsifalreadyinproduction;3)Editthemigrationfiledirectly,butthisisrisky;

Last Laravel version: Performance GuideLast Laravel version: Performance GuideMay 13, 2025 am 12:04 AM

ToboostperformanceinthelatestLaravelversion,followthesesteps:1)UseRedisforcachingtoimproveresponsetimesandreducedatabaseload.2)OptimizedatabasequerieswitheagerloadingtopreventN 1queryissues.3)Implementroutecachinginproductiontospeeduprouteresolution.

The Most Recent Laravel Version: Discover What's NewThe Most Recent Laravel Version: Discover What's NewMay 12, 2025 am 12:15 AM

Laravel10introducesseveralkeyfeaturesthatenhancewebdevelopment.1)Lazycollectionsallowefficientprocessingoflargedatasetswithoutloadingallrecordsintomemory.2)The'make:model-and-migration'artisancommandsimplifiescreatingmodelsandmigrations.3)Integration

Laravel Migrations Explained: Create, Modify, and Manage Your DatabaseLaravel Migrations Explained: Create, Modify, and Manage Your DatabaseMay 12, 2025 am 12:11 AM

LaravelMigrationsshouldbeusedbecausetheystreamlinedevelopment,ensureconsistencyacrossenvironments,andsimplifycollaborationanddeployment.1)Theyallowprogrammaticmanagementofdatabaseschemachanges,reducingerrors.2)Migrationscanbeversioncontrolled,ensurin

Laravel Migration: is it worth using it?Laravel Migration: is it worth using it?May 12, 2025 am 12:10 AM

Yes,LaravelMigrationisworthusing.Itsimplifiesdatabaseschemamanagement,enhancescollaboration,andprovidesversioncontrol.Useitforstructured,efficientdevelopment.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools