定制 jackbayliss/laravel-model-connection 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

jackbayliss/laravel-model-connection

Composer 安装命令:

composer require jackbayliss/laravel-model-connection

包简介

Define separate read/write database connections per Eloquent model.

README 文档

README

Latest Version on Packagist GitHub Tests Action Status

Define separate read and write database connections per Eloquent model.

Why?

Laravel has built-in support for read/write connection splitting, but it's configured at the connection level in config/database.php which means, every model using that connection shares the same read/write behaviour:

// config/database.php ...this applies globally to all models on this connection
'mysql' => [
    'read'  => ['host' => '192.168.1.2'],
    'write' => ['host' => '196.168.1.3'],
],

There's no first-party way to set specific models to only read. The alternative is manually calling ::on() or ->setConnection() everywhere you query, which is easy to forget and scatters connection logic across your codebase:

// Without this package ...you have to remember to do this every time
User::on('mysql_replica')->where('active', true)->get();
Post::on('mysql_replica')->latest()->get();

This package gives you control over read and write connections per model without touching your connection config, and without sprinkling ::on() calls throughout your code. This is extremely useful if you know certain models can be deferred to a replica, and certain models are required instantly.

Supports

  • Laravel 12

Installation

composer require jackbayliss/laravel-model-connection

Usage

Add the HasReadWriteConnection trait to your model and define $readConnection and $writeConnection:

use JackBayliss\LaravelModelConnection\Traits\HasReadWriteConnection;

class User extends Model
{
    use HasReadWriteConnection;

    protected $readConnection  = 'mysql_replica';
    protected $writeConnection = 'mysql_primary';
}

All reads (first(), get(), relationships, eager loads) will go to mysql_replica, and all writes (create(), update(), delete()) will go to mysql_primary.

If $readConnection or $writeConnection are not set, the trait falls back to the model's default $connection.

Enum Support

You can use a backed enum instead of a plain string:

enum DatabaseConnection: string
{
    case Primary = 'mysql_primary';
    case Replica = 'mysql_replica';
}

class User extends Model
{
    use HasReadWriteConnection;

    protected $readConnection  = DatabaseConnection::Replica;
    protected $writeConnection = DatabaseConnection::Primary;
}

Runtime Override

You can override the connections at runtime using the fluent setters:

$user = (new User)
    ->setReadConnection('mysql_replica_2')
    ->setWriteConnection('mysql_primary_2');

Available Methods

Method Description
getReadConnection() Returns the Connection instance for reads
getWriteConnection() Returns the Connection instance for writes
getReadConnectionName() Returns the read connection name as a string
getWriteConnectionName() Returns the write connection name as a string
setReadConnection($connection) Override the read connection at runtime
setWriteConnection($connection) Override the write connection at runtime

Using with Factories

By default, factories will write to your model's $writeConnection (default if empty). In a real application this is correct as replication will sync the data to your read replica.

However, in tests you typically want factory-created records to be immediately readable via the model. Since reads go to $readConnection, you need factory writes to land there too.

Add the HasReadWriteConnectionFactory trait to your factory:

use JackBayliss\LaravelModelConnection\Traits\HasReadWriteConnectionFactory;

class UserFactory extends Factory
{
    use HasReadWriteConnectionFactory;

    protected $model = User::class;

    public function definition(): array
    {
        return [
            'name' => fake()->name(),
        ];
    }
}

This redirects the factory's save to the read connection, so User::factory()->create() produces records that User::find(), User::get(), etc. can retrieve.

If you already have a configure() method, call withReadWriteConnection() inside it instead:

public function configure(): static
{
    return $this->withReadWriteConnection()->afterCreating(function (User $user) {
        // your own logic
    });
}

Testing

The package includes a full test suite covering read/write routing, enum support, runtime overrides, and fallback behaviour. To run the tests:

composer test

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

jackbayliss/laravel-model-connection 适用场景与选型建议

jackbayliss/laravel-model-connection 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1 次下载、GitHub Stars 达 6, 最近一次更新时间为 2026 年 02 月 21 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「database」 「laravel」 「eloquent」 「read-write」 「connections」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 jackbayliss/laravel-model-connection 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 jackbayliss/laravel-model-connection 我们能提供哪些服务?
定制开发 / 二次开发

基于 jackbayliss/laravel-model-connection 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 1
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 6
  • 点击次数: 29
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 6
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-02-21