PHP code example of jackbayliss / laravel-model-connection
1. Go to this page and download the library: Download jackbayliss/laravel-model-connection library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
jackbayliss / laravel-model-connection example snippets
// 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'],
],
// 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();
use JackBayliss\LaravelModelConnection\Traits\HasReadWriteConnection;
class User extends Model
{
use HasReadWriteConnection;
protected $readConnection = 'mysql_replica';
protected $writeConnection = 'mysql_primary';
}
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;
}
$user = (new User)
->setReadConnection('mysql_replica_2')
->setWriteConnection('mysql_primary_2');
use JackBayliss\LaravelModelConnection\Traits\HasReadWriteConnectionFactory;
class UserFactory extends Factory
{
use HasReadWriteConnectionFactory;
protected $model = User::class;
public function definition(): array
{
return [
'name' => fake()->name(),
];
}
}
public function configure(): static
{
return $this->withReadWriteConnection()->afterCreating(function (User $user) {
// your own logic
});
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.