PHP

Configure Custom Database Connections and Table Names

Learn how to configure Eloquent models to use a different database connection or a custom table name than Laravel's default conventions.

// In app/Models/AnalyticsRecord.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class AnalyticsRecord extends Model
{
    /**
     * The database connection that should be used by the model.
     *
     * @var string
     */
    protected $connection = 'mysql_analytics'; // Uses the 'mysql_analytics' connection defined in config/database.php

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'website_analytics_data'; // Overrides default 'analytics_records'

    /**
     * The primary key for the model.
     *
     * @var string
     */
    protected $primaryKey = 'record_id'; // Overrides default 'id'

    /**
     * Indicates if the IDs are auto-incrementing.
     *
     * @var bool
     */
    public $incrementing = false; // Set to false for UUIDs or custom primary keys

    /**
     * The "type" of the auto-incrementing ID.
     *
     * @var string
     */
    protected $keyType = 'string'; // Useful for UUID primary keys
}

// Example config/database.php entry for 'mysql_analytics'
/*
'connections' => [
    // ... default connections

    'mysql_analytics' => [
        'driver' => 'mysql',
        'host' => env('DB_ANALYTICS_HOST', '127.0.0.1'),
        'port' => env('DB_ANALYTICS_PORT', '3306'),
        'database' => env('DB_ANALYTICS_DATABASE', 'analytics_db'),
        'username' => env('DB_ANALYTICS_USERNAME', 'forge'),
        'password' => env('DB_ANALYTICS_PASSWORD', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],
],
*/
How it works: By default, Eloquent assumes certain conventions like using the `default` database connection and a pluralized snake_case version of the model name for the table. However, you can easily override these defaults within your model. The `$connection` property specifies which database connection (defined in `config/database.php`) to use, while `$table` allows you to define a custom table name. You can also customize the `$primaryKey`, `$incrementing` behavior, and `$keyType` for non-standard primary keys like UUIDs, providing flexibility for diverse database schemas.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs