Skip to content

Bug Report: Inability to Disable Top-Level _id Aliasing in Laravel MongoDB Package #3392

Open
@Danilim04

Description

@Danilim04

Bug Report: Inability to Disable Top-Level _id Aliasing in Laravel MongoDB Package

Description:
The mongodb/laravel-mongodb package currently provides a configuration option rename_embedded_id_field to disable automatic renaming of _id fields only for embedded documents. However, there is no corresponding option to disable top-level _id aliasing. As a result:

  • Models with a custom protected $primaryKey = 'id'; still have their primary key queries (find(), findOrFail(), whereKey(), etc.) hard-coded to use the MongoDB _id field.
  • Disabling rename_embedded_id_field has no effect on the top-level _id behavior.
  • Route Model Binding and direct lookups by $model->id do not work as expected when using a string or UUID primary key named id.

Steps to Reproduce:

  1. Set up a Laravel model extending Jenssegers\Mongodb\Eloquent\Model with:

    class Invoice extends Model {
        protected $primaryKey = 'id';
    }
  2. In config/database.php, configure:

    'connections' => [
        'mongodb' => [
            'driver' => 'mongodb',
            // ...
            'rename_embedded_id_field' => false,
        ],
    ],
  3. Attempt to retrieve a document via Invoice::find($idString) or via route model binding on the id field.

Expected Behavior:

  • The package should respect the model’s $primaryKey and use the id field for top-level queries when rename_embedded_id_field is set to false.

Actual Behavior:

  • The package continues to query against the _id field, ignoring the custom primaryKey, making it impossible to use a string or UUID id as the primary key without overriding core builder methods.

Impact:
This limitation prevents the use of non-ObjectId primary keys at the top level and breaks Laravel features like route model binding for string or UUID keys.

Workarounds:
Currently, the only way to work around this issue is to override multiple internal builder methods (find, whereKey, findOrFail, etc.) or to run native MongoDB queries manually, which is not sustainable.

Request:
Please introduce a new configuration option (e.g., rename_id_field) or enhance existing logic so that top-level _id aliasing can be disabled, allowing the package to use the model’s $primaryKey for all primary key operations.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions